[
hash table
counter
sliding window
]
Leetcode 0219 Contains Duplicate II
Problem statement
https://leetcode.com/problems/contains-duplicate-ii/
Solution
Go through array, and keep the last index for each number in hash table. Check if it was long time ago or not.
Complexity
Time and space complexity is O(n)
.
Code
class Solution:
def containsNearbyDuplicate(self, nums, k):
d = defaultdict(list)
for i, num in enumerate(nums):
d[num].append(i)
for s in d.values():
if any(b-a <= k for a,b in zip(s, s[1:])): return True
return False