219. Contains Duplicate II
Asked at 12Meta61Bloomberg57Google49Amazon49Microsoft44tcs59Arista Networks78Airbnb71Netflix69Accenture61Adobe55Zoho42
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
assert Solution().containsNearbyDuplicate([1, 2, 3, 1], 3) is True
assert Solution().containsNearbyDuplicate([1, 0, 1, 1], 1) is True
assert Solution().containsNearbyDuplicate([1, 2, 3, 1, 2, 3], 2) is False
assert Solution().containsNearbyDuplicate([1, 1], 0) is False
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> window = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (!window.add(nums[i])) return true;
if (window.size() > k) window.remove(nums[i - k]);
}
return false;
}
}
func containsNearbyDuplicate(nums []int, k int) bool {
window := map[int]bool{} // the last k values
for i, x := range nums {
if window[x] {
return true
}
window[x] = true
if len(window) > k {
delete(window, nums[i-k])
}
}
return false
}