Contains Duplicate II
Check whether an array has two equal values at most k indices apart, using a window of recent values kept in a set.
Given an array of integers numsktrueijknums[i] == nums[j]abs(i - j) <= kfalse
Example 1
Output: true
Explanation: the two 1s, at indices 0 and 3, are 3 apart.
Example 2
Output: true
Explanation: the 1s at indices 2 and 3 are 1 apart.
Example 3
Output: false
Explanation: each value appears twice, but always 3 indices apart.
The Idea
Imagine reading a long list of numbers one at a time and asking about each new number: have I seen this one recently? Not anywhere earlier in the list, only among the last few numbers. Here "recently" has an exact meaning: at most k
Take Example 3, [1, 2, 3, 1, 2, 3]k = 2false
So, standing at an index ii - ki - 1k
Look at the picture below. It has two rows, and both stop at index 3, marked i = 3k
In the top row, Example 3 with k = 2i = 3[1, 2, 3, 1]k = 3true
When iii - kk
So the check at each index shrinks to one question: is nums[i]
Solution Approach
Turning that idea into code means settling three things: how to check the window quickly, how to keep it at k
Checking the window quickly
Why not simply compare nums[i]kkk = 50,000
A HashSetHashSetk
Keeping the window at k values
When does a value leave the set? After checking nums[i]knums[i - k]i + 1
For the first kki = ki - k
Why a set is enough
Could the window hold the same value twice, so that removing one copy also loses the other? No. A value goes in only after the check that it is not already there, and finding it there ends the search with truenums[i - k]
Java Solution
The method containsNearbyDuplicate
- First, create an empty
namedHashSet . It will hold the values at the lastwindow indices.k - Walk through the array with one loop, moving the index
from the first element to the last.i - For each
, addi withnums[i] . This call returnswindow.add(nums[i]) when the value is already in the set. That means an equal value sits at mostfalse indices back, so returnk right away.true - If
now holds more thanwindow values, removek , the value that has become too far back.nums[i - k] - If the loop ends without a match, return
.false
The main[1, 1]k = 0[7, 4, 7]k
import java.util.HashSet;
import java.util.Set;
public class ContainsDuplicatesII {
public static boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> window = new HashSet<>(); // values at the last k indices
for (int i = 0; i < nums.length; i++) {
if (!window.add(nums[i])) {
return true; // nums[i] was already in the window
}
if (window.size() > k) {
window.remove(nums[i - k]); // index i - k is now too far back
}
}
return false;
}
public static void main(String[] args) {
System.out.println(containsNearbyDuplicate(new int[] {1, 2, 3, 1}, 3));
System.out.println(containsNearbyDuplicate(new int[] {1, 0, 1, 1}, 1));
System.out.println(containsNearbyDuplicate(new int[] {1, 2, 3, 1, 2, 3}, 2));
System.out.println(containsNearbyDuplicate(new int[] {1, 1}, 0));
System.out.println(containsNearbyDuplicate(new int[] {}, 5));
System.out.println(containsNearbyDuplicate(new int[] {7, 4, 7}, 100));
}
}
Running it prints:
true
true
false
false
false
true
Look at the third line, false[1, 2, 3, 1, 2, 3]k = 2true
The fourth line is false[1, 1]k = 0false
The last line is truek = 100k
The check that removes old values is easy to get off by one. If it is window.size() >= knums[i - k + 1]k - 1falsei
The original implementation,
Complexity
Each index costs one lookup-and-add on the set and at most one remove.
- Time: O(n), because the loop visits each of the n values once, and
andadd on aremove take constant time on average. Comparing each value with the k before it would take O(n × k).HashSet - Space: O(min(n, k)), because the set holds at most
values, just after an add, and never more than the n values in the array.k + 1
Without the distance limit, the question becomes