Given an integer array nums
and an integer k
, determine if there are two distinct indices i
and j
in the array such that nums[i] == nums[j]
and abs(i - j) <= k
.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Explanation: The indices 0 and 3 satisfy the condition because nums[0] == nums[3] and abs(0 - 3) <= 3.
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Explanation: The indices 0 and 2 satisfy the condition because nums[0] == nums[2] and abs(0 - 2) <= 1. Also, indices 2 and 3 satisfy the condition because nums[2] == nums[3] and abs(2 - 3) <= 1.
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Explanation: Although there are duplicate numbers, no two duplicate numbers are within a distance of 2.
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
0 <= k <= 10^5
The naive solution would involve iterating through all possible pairs of indices (i, j) in the array and checking if nums[i] == nums[j]
and abs(i - j) <= k
. This would involve nested loops.
def containsNearbyDuplicate_naive(nums, k):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j] and abs(i - j) <= k:
return True
return False
O(n^2), where n is the length of the nums
array, due to the nested loops.
O(1), as we are using only a constant amount of extra space.
A more efficient solution involves using a hash set (or dictionary) to store the elements encountered so far, along with their indices. For each element, check if it exists in the set. If it does, check if the absolute difference between the current index and the stored index is less than or equal to k
. If it is, return true
. Otherwise, update the index of the element in the hash set. If the element is not in the hash set, add it along with its index. This way you only need to iterate once.
def containsNearbyDuplicate(nums, k):
num_map = {}
for i, num in enumerate(nums):
if num in num_map and abs(i - num_map[num]) <= k:
return True
num_map[num] = i
return False
O(n), where n is the length of the nums
array, as we iterate through the array only once.
O(n) in the worst case, where n is the length of the nums
array. This is because, in the worst-case scenario, all elements in the array are distinct, and we would store all of them in the hash set.
nums
is empty, the function should return false
because there are no elements to compare.k
is 0, the function should return true
if there are duplicate elements at the same index, which is impossible given the distinct indices constraint. Thus, when k
is 0, it will return false.k
is very large (e.g., greater than or equal to the length of the array), the function should still work correctly, comparing all possible pairs of indices.k
of each other.false
if the array contains no duplicate values.