Problem
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
.
Examples
Example 1:
Input nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Solution
Method 1 - Using HashSet and sliding window
We can follow following steps:
- Initialize a HashSet: To store elements within the current sliding window of size
k
. - Iterate through the array: Using a for loop to process each element.
- Remove out-of-range elements: If the current index
i
exceedsk
, remove the element that isk+1
positions behind from the set to maintain the window size. - Add current element to the set: Try adding the current element to the
HashSet
. - Check for duplicates: If the element already exists in the set, return
true
(duplicate found within range).
- Remove out-of-range elements: If the current index
- Return false if no duplicates are found: After iterating through all elements in the array.
Code
Java
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) {
set.remove(nums[i-k-1]);
}
if(!set.add(nums[i])) {
return true;
}
}
return false;
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(k)
Method 2 - Using HashMap
We can follow following steps:
- Initialize a HashMap: To store elements and their corresponding indices.
- Iterate through the array: Using a for loop to process each element.
- Check if the element is already in the map: Determine if the current element has been seen before.
- Check index difference: If the element is in the map, compare the current index with the stored index. If the difference is less than or equal to
k
, returntrue
. - Update the map: Store the current element and its index in the map.
- Return false if no duplicates are found: After iterating through all elements in the array.
Code
Java
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
if (i - map.get(nums[i]) <= k) {
return true;
}
}
map.put(nums[i], i);
}
return false;
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)