Contains Duplicate II

EasyHash Tables · Sliding Window🧩 Hashing & CountingLeetCode #219 ↗Updated

Problem

Given an integer array nums and an integer k, decide whether some value appears at two different indices i and j that are at most k apart (|i - j| ≤ k).
Input[1,2,3,1], k=3Outputtrue
Input[1,0,1,1], k=1Outputtrue
Input[1,2,3,1,2,3], k=2Outputfalse

1 ≤ n ≤ 105  ·  -109 ≤ nums[i] ≤ 109  ·  0 ≤ k ≤ 105

Try it yourself

Java
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
For index i only the previous k elements matter. Keep exactly those in a hash set window: a hit on insert means a close duplicate.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceCheck the Next k Elements

Time O(n · min(n,k))Space O(1)

For every i, compare nums[i] with each nums[j] for j in (i, i+k]. Any equal pair in that range is a valid answer.

Java
public boolean containsNearbyDuplicate(int[] nums, int k) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j <= i + k && j < nums.length; j++) {
            if (nums[i] == nums[j]) return true;
        }
    }
    return false;
}

No extra memory, but ~1010 comparisons when n and k are large.

At a glance

LevelApproachTimeSpace
Brute ForceCheck the Next k ElementsO(n · min(n,k))O(1)
BetterHash Map of Last-Seen IndexO(n)O(n)
OptimalSliding Window Hash SetO(n)O(min(n,k))
Common pitfalls
  • Off-by-one eviction: after inserting, drop nums[i-k] (not nums[i-k-1]).
  • Using < k instead of ≤ k — distance exactly k counts.
  • Forgetting k = 0: two different indices can never be 0 apart → always false.
Interview tips
  • Clarify: the indices must differ, and the bound is inclusive.
  • Mention the map trade-off: simpler but O(n) space vs. O(k) for the window.
  • Bridge to Contains Duplicate III: swap the set for a TreeSet or buckets.
Pattern
Fixed-size sliding window + hash set → “does a repeat occur within distance k?”
My notes saved in this browser