Given an integer array
Output: true
Output: true
Output: false
Constraints:
1 <= nums.length <= 105 -109 <= nums[i] <= 109 0 <= k <= 105
Contents
Solution 1 - Using sliding window technique, and a HashSet find if there is a duplicate element within window size of K
In this approach, we are going to apply sliding window technique, using two pointers
Implementation steps:
-
First, we will create three variables
left ,right that we will use to adjust the window, and aHashSet ,dups to check the duplicate of an element. Initializeleft=0 andright=0 , that is the beginning window size. -
Next, run a
while loop untilright pointer reaches end of array, and check:-
If the difference between right and left pointers are greater than K: This means that we are going out of window size
k , so removeleft pointer element fromdups to keep the window size withink , and also incrementleft pointer. -
If the right pointer element is found in HashSet: return
true , since a duplicate found within the window size ofk . -
Finally, add
right pointer element to thedups and then incrementright pointer.
-
If the difference between right and left pointers are greater than K: This means that we are going out of window size
-
If there is no duplicate found, at the end return
false .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(k) for the
Above implementations source code can be found at