Advertisement
smj007

Untitled

Apr 6th, 2025
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. # Solution that works - but is not optimized
  2.  
  3. class Solution:
  4.     def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
  5.         """check duplicates for two distinct indices"""
  6.  
  7.         hashmap = defaultdict(list)
  8.         for i, num in enumerate(nums):
  9.             hashmap[num].append(i)
  10.  
  11.         for num in hashmap:
  12.             if len(hashmap[num]) <= 1:
  13.                 continue
  14.  
  15.             for i in range(1, len(hashmap[num])):
  16.                 if abs(hashmap[num][i] - hashmap[num][i-1])<=k:
  17.                     return True
  18.  
  19.         return False
  20.        
  21. # Solution which works and slightly optimized with sliding window
  22. TC: O(n) - when you have to go all the way to the last element
  23. 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.
  24. class Solution:
  25.     def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
  26.         """check duplicates for two distinct indices"""
  27.  
  28.         # store last previously seen index
  29.         hashmap = defaultdict(int)
  30.  
  31.         for i in range(len(nums)):
  32.             # if you saw it previously
  33.             if nums[i] in hashmap and abs(hashmap[nums[i]]-i)<=k:
  34.                 return True
  35.  
  36.             # not previously seen; update the last see
  37.             hashmap[nums[i]] = i
  38.  
  39.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement