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 nums and a number k, return true if the same value appears at two different indices i and j that are at most k apart. In other words, nums[i] == nums[j] and abs(i - j) <= k. Otherwise return false.

Example 1
Input: nums = [1, 2, 3, 1], k = 3
Output: true
Explanation: the two 1s, at indices 0 and 3, are 3 apart.
Example 2
Input: nums = [1, 0, 1, 1], k = 1
Output: true
Explanation: the 1s at indices 2 and 3 are 1 apart.
Example 3
Input: nums = [1, 2, 3, 1, 2, 3], k = 2
Output: false
Explanation: each value appears twice, but always 3 indices apart.
Solution

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 indices back.

Take Example 3, [1, 2, 3, 1, 2, 3] with k = 2. The 1 at index 3 has an equal value at index 0, but that is 3 indices back, one too many. The two 2s, at indices 1 and 4, and the two 3s, at indices 2 and 5, are 3 apart as well. Every value repeats, yet the answer is false.

So, standing at an index i, which earlier numbers do we actually need to look at? Only the ones at indices i - k up to i - 1, the last k of them. Anything before those is too far away, for this index and for every later one.

Look at the picture below. It has two rows, and both stop at index 3, marked i = 3. The dashed box around the last k values before it is labelled "window".

At index i = 3, the window holds the values at the last k indices. In Example 3, with k = 2, the window holds 2 and 3, and the 1 at index 0 is outside it. In Example 1, with k = 3, the window also holds the 1 at index 0, so the answer is true.

In the top row, Example 3 with k = 2, the window holds 2 and 3. The 1 at index 0 is outside it, so the 1 at i = 3 has no match. The bottom row is Example 1, [1, 2, 3, 1] with k = 3. Now the window reaches back to index 0, the 1 there is inside it, and the answer is true.

When i moves one step right, the window moves with it. The value at the old i joins, and the value at the old i - k drops out, because it is now too far back. A stretch of neighbouring elements that moves along an array like this is called a sliding window. Here its size is fixed at k, except near the start, where fewer values exist.

So the check at each index shrinks to one question: is nums[i] one of the values in the window?

Solution Approach

Turning that idea into code means settling three things: how to check the window quickly, how to keep it at k values, and why a plain set is enough to hold it.

Checking the window quickly

Why not simply compare nums[i] with each of the k values before it? That is correct, but it takes up to k comparisons per index, about n × k steps for an array of n numbers. With 100,000 numbers and k = 50,000, that is a few billion comparisons.

A HashSet does better. It is Java's set backed by a hash table: it stores each value once and finds a value by its hash code, in one step on average, however many values it holds. Keeping the window's values in a HashSet turns k comparisons into one lookup.

Keeping the window at k values

When does a value leave the set? After checking nums[i], add it, since it belongs to the window of the next index. If the set now holds more than k values, the oldest one, nums[i - k], is too far back for index i + 1, so remove it.

For the first k indices nothing is removed, because nothing is too far back yet. The set first grows past k values at index i = k, so i - k is never negative.

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 true. So the window never holds a repeat, and removing nums[i - k] removes exactly the value of that one index. A map that counts copies is not needed.

Java Solution

The method containsNearbyDuplicate works in these steps:

  1. First, create an empty HashSet named window. It will hold the values at the last k indices.
  2. Walk through the array with one loop, moving the index i from the first element to the last.
  3. For each i, add nums[i] with window.add(nums[i]). This call returns false when the value is already in the set. That means an equal value sits at most k indices back, so return true right away.
  4. If window now holds more than k values, remove nums[i - k], the value that has become too far back.
  5. If the loop ends without a match, return false.

The main method runs the three examples, then [1, 1] with k = 0, an empty array, and [7, 4, 7] with a k far larger than the array.

Java
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:

Output
true
true
false
false
false
true

Look at the third line, false. In [1, 2, 3, 1, 2, 3] every value repeats, but always 3 indices apart, one more than k = 2 allows. Above it, Examples 1 and 2 both print true.

The fourth line is false for [1, 1] with k = 0. Two different indices are always at least 1 apart, so no pair can count. In the code, the set is emptied right after each add, so the second 1 finds nothing. The fifth line, false, is the empty array, where the loop never runs.

The last line is true: with k = 100 the set never grows past k, nothing is removed, and the second 7 finds the first one 2 indices back.

The check that removes old values is easy to get off by one. If it is window.size() >= k and the code removes nums[i - k + 1], the window keeps only k - 1 values. That version returns false for Example 1, because it removes the first 1 while i is still 2, one step too early.

The original implementation, ContainsDuplicatesII.java, is on GitHub.

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 add and remove on a HashSet take constant time on average. Comparing each value with the k before it would take O(n × k).
  • Space: O(min(n, k)), because the set holds at most k + 1 values, just after an add, and never more than the n values in the array.

Without the distance limit, the question becomes Contains Duplicate, where a set of every value seen so far is enough.