Contains Duplicate II
Given an integer array numsktrueijnums[i] == nums[j]abs(i - j) <= k
Example 1
Input: nums = [1,2,3,1], k = 3
Output: true
Output: true
Example 2
Input: nums = [1,0,1,1], k = 1
Output: true
Output: true
Example 3
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105
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 leftrightkright - left
Implementation steps:
-
First, we will create three variables
,left that we will use to adjust the window, and aright ,HashSet to check the duplicate of an element. Initializedups andleft=0 , that is the beginning window size.right=0 -
Next, run a
loop untilwhile pointer reaches end of array, and check:right-
If the difference between right and left pointers are greater than K: This means that we are going out of window size
, so removek pointer element fromleft to keep the window size withindups , and also incrementk pointer.left -
If the right pointer element is found in HashSet: return
, since a duplicate found within the window size oftrue .k -
Finally, add
pointer element to theright and then incrementdups pointer.right
-
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
Java
import java.util.HashSet;
public class ContainsDuplicatesII {
static boolean containsNearbyDuplicate(int[] nums, int k) {
int left = 0;
int right = 0;
HashSet<Integer> dups = new HashSet<>();
while(right < nums.length) {
if(right-left > k) {
dups.remove(nums[left]);
left++;
}
if(dups.contains(nums[right])) {
return true;
}
dups.add(nums[right]);
right++;
}
return false; // if nothing found
}
public static void main(String[] args) {
System.out.println(containsNearbyDuplicate(new int[]{1, 2, 3, 1}, 3));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
Space complexity: O(k) for the HashSetk
Above implementations source code can be found at