Skip to main content
Back to problems
#220
Hard Algorithms

Contains duplicate iii

Array Sliding Window Sorting Bucket Sort Ordered Set
24.5% acceptance
Jan 12, 2026
1288
143
You are given an integer array nums and two integers indexDiff and valueDiff. Find a pair of indices (i, j) such that: i != j, abs(i - j) <= indexDiff. abs(nums[i] - nums[j]) <= valueDiff, and Return true if such pair exists or false otherwise.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn contains_nearby_almost_duplicate(nums: Vec<i32>, index_diff: i32, value_diff: i32) -> bool {
    use std::collections::BTreeSet;
    let mut set = BTreeSet::new();
    let k = index_diff as usize;
    let t = value_diff as i64;
    
    for (i, &num) in nums.iter().enumerate() {
      let num = num as i64;
      
      if let Some(&_val) = set.range(num - t..=num + t).next() {
        return true;
      }
      
      set.insert(num);
      if i >= k {
        set.remove(&(nums[i - k] as i64));
      }
    }
    false
  }
}