Skip to main content
Back to problems
#219
Easy Algorithms

Contains duplicate ii

Array Hash Table Sliding Window
50.8% acceptance
Jan 12, 2026
7427
3312
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn contains_nearby_duplicate(nums: Vec<i32>, k: i32) -> bool {
    let mut map = std::collections::HashMap::new();
    for (i, &num) in nums.iter().enumerate() {
      if let Some(&prev_i) = map.get(&num) {
        if i - prev_i <= k as usize {
          return true;
        }
      }
      map.insert(num, i);
    }
    false
  }
}