
[LeetCode] 219. Contains Duplicate II

Use a sliding window of size
kwith a set.
k recent elements.k.k, remove the oldest element.class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
# Sliding window with size k
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