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:
|
|
Example 2:
|
|
Example 3:
|
|
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
|
|
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
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)