SDE & MLE Prep

219. Contains Duplicate II

Problem

Decide whether there are two indices i ≠ j with nums[i] == nums[j] and |i − j| ≤ k.

Example: nums = [1,2,3,1], k = 3 → true; nums = [1,2,3,1,2,3], k = 2 → false

Keep a set of the last k values. A value already in the set is a duplicate within distance k. Evict nums[i − k] once the window holds more than k values.

Complexity: O(n) time, O(k) space.

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        window = set()
        for i, x in enumerate(nums):
            if x in window:
                return True
            window.add(x)
            if len(window) > k:
                window.remove(nums[i - k])
        return False