class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && (map.get(nums[i]) - i) <= k) { return true; } map.put(nums[i], i); } return false; } } /* i != j abs(i-j) <= k T: O(n) S: O(n) */
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: dict = {} for i, v in enumerate(nums): if v in dict and i - dict[v] <= k: return True dict[v] = i return False
Last updated 2 years ago