Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Solution that works - but is not optimized
- class Solution:
- def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
- """check duplicates for two distinct indices"""
- hashmap = defaultdict(list)
- for i, num in enumerate(nums):
- hashmap[num].append(i)
- for num in hashmap:
- if len(hashmap[num]) <= 1:
- continue
- for i in range(1, len(hashmap[num])):
- if abs(hashmap[num][i] - hashmap[num][i-1])<=k:
- return True
- return False
- # Solution which works and slightly optimized with sliding window
- TC: O(n) - when you have to go all the way to the last element
- SC: The space complexity is O(n) in the worst case when all elements are unique. The space complexity becomes O(k) if duplicates are present within the range k since the hashmap will only hold the most recent occurrences.
- class Solution:
- def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
- """check duplicates for two distinct indices"""
- # store last previously seen index
- hashmap = defaultdict(int)
- for i in range(len(nums)):
- # if you saw it previously
- if nums[i] in hashmap and abs(hashmap[nums[i]]-i)<=k:
- return True
- # not previously seen; update the last see
- hashmap[nums[i]] = i
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement