Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
k?
k can be any non-negative integer within the constraints of typical LeetCode problems, commonly up to 10^5.nums array is empty or contains a single element?
nums array is empty or has only one element, return false since no indices i and j can satisfy the condition.nums and k are always valid inputs.We need to track the indices of elements we have seen while traversing the array. Here’s a concise plan to achieve this:
k, return true.false.def containsNearbyDuplicate(nums, k):
index_map = {}
for i, num in enumerate(nums):
if num in index_map and i - index_map[num] <= k:
return True
index_map[num] = i
return False
Time Complexity: O(n), where n is the number of elements in the nums array. We traverse the list once, and dictionary operations (insertion and lookup) are on average O(1).
Space Complexity: O(min(n, k)), as the dictionary will at most store k elements due to the sliding window constraint.
This solution efficiently checks for duplicate elements within the given index distance constraint, ensuring optimal performance for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?