← Back to Leo Academy Masterclass

Problem #219: Contains Duplicate II

Easy Hashmap

Intuition & Strategy Breakdown

Use a sliding window hash set of size K. If current element exists in set return true, otherwise add to set and evict oldest element beyond distance K.

Python Solution

def containsNearbyDuplicate(nums, k):
    seen = set()
    for i, num in enumerate(nums):
        if num in seen:
            return True
        seen.add(num)
        if len(seen) > k:
            seen.remove(nums[i - k])
    return False

Java Solution

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set seen = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (seen.contains(nums[i])) return true;
            seen.add(nums[i]);
            if (seen.size() > k) {
                seen.remove(nums[i - k]);
            }
        }
        return false;
    }
}
Watch Interactive Video on Leo Academy Main App