Subarrays with K Different Integers

Count the subarrays of an array that hold exactly k different values.

You are given an array of integers nums and a number k. A subarray is a run of numbers that sit next to each other in the array, such as [2, 1, 2] in [1, 2, 1, 2, 3]. Return how many subarrays hold exactly k different values.

Example 1
Input: nums = [1, 2, 1, 2, 3], k = 2
Output: 7
Explanation: [1, 2], [2, 1], [1, 2], [2, 3], [1, 2, 1], [2, 1, 2], [1, 2, 1, 2].
Example 2
Input: nums = [1, 2, 1, 3, 4], k = 3
Output: 3
Explanation: [1, 2, 1, 3], [2, 1, 3], [1, 3, 4].
Solution

The Idea

Picture the numbers of Example 1 as a row of beads: 1, 2, 1, 2, 3. You cut out one unbroken piece of the row and ask how many different values it holds. The piece [2, 1, 2] has three beads but only two different values, 1 and 2. The whole row holds three: 1, 2 and 3. Seven pieces hold exactly two, and Example 1 lists them.

A row of five numbers has 15 subarrays: five of length 1, four of length 2, and so on down to one of length 5. Checking each of them is fine here. With 100,000 numbers, though, there are about 5 billion. Can we count the right ones without looking at each?

It helps to group the subarrays by where they end. Take the ones whose last number is at index 3 (counting from 0), the second 2. Look at the picture below.

The subarrays of 1, 2, 1, 2, 3 whose right end is index 3. Start 3 gives [2], one value. Starts 2, 1 and 0 give two values. At most 2 values: 4 subarrays. At most 1 value: 1 subarray. Exactly 2 values: 4 - 1 = 3.

The blue box marks the right end, index 3. Starting there gives [2], one value. Moving the start one place left, to index 2, adds a 1 and gives [1, 2], two values. Starts 1 and 0 only add more 1s and 2s, so they stay at two values.

Moving the start left can add values but never takes one away. So the starts that give at most 2 values form one unbroken range that ends at the right end: here starts 0 to 3, four subarrays. The starts that give at most 1 value form a range too: start 3 only, one subarray.

A subarray with exactly 2 values is one with at most 2 values, but not at most 1. So there are 4 - 1 = 3 of them, the three orange pieces. That is the key insight: the count for exactly k is the count for at most k minus the count for at most k - 1.

Why take this detour instead of counting exactly 2 directly? The starts with exactly 2 values also form a range, but it can stop short of the right end, as start 3 shows. So it has two edges to track. The range for "at most" always reaches the right end, so it has only one edge, the leftmost start that still works.

Solution Approach

Turning that idea into code means settling three things: how to count the subarrays with at most k values, how to know how many different values a run of numbers holds, and how to get exactly k from two such counts.

Counting subarrays with at most k values

For each right end, how do we find the leftmost start that still has at most k values? The simple way walks left from the right end every time. For an array of n numbers, that takes up to n steps for each of the n right ends, about n²/2 steps in all.

A faster way keeps a marker, left, on that leftmost start, and a second marker, right, on the right end. When right moves one place, the new number can only add a value. So the leftmost good start never moves back: left only moves right, and only while the numbers from left to right hold more than k values. After that, every start from left to right works, so right - left + 1 subarrays end at right.

The run of numbers between the two markers is called a window, and moving both of its ends forward like this is called the sliding-window technique. Each marker passes each index once, so one count takes about 2n steps, not n²/2.

Keeping count of the values in the window

How does the code know how many different values the window holds? It keeps a HashMap from each value to the number of times it appears in the window. When right takes in a number, its count goes up by one. When left moves past a number, its count goes down by one, and at 0 the value is removed from the map. The size of the map is then the number of different values in the window.

From "at most" to "exactly"

How do two counts give the answer? Run the window count once with k and once with k - 1, and subtract the second from the first. When k is 1, the second count asks for at most 0 values. No subarray qualifies, and the window code handles that on its own: left moves past right every time and adds 0.

Java Solution

The method subarraysWithKDistinct works in these steps:

  1. First, call the helper atMost twice, with k and with k - 1, and return the first result minus the second.
  2. Inside atMost, create the map count, from value to how often it appears in the window. Set left and result to 0.
  3. A loop moves right from the first index to the last. At each step, count.merge(nums[right], 1, Integer::sum) adds 1 to the count of the new number, or stores 1 if the value is new.
  4. Inside, a second loop shrinks the window while count.size() is more than k. It lowers the count of nums[left] by one, removes that value from the map when its count reaches 0, and moves left one place right.
  5. Add right - left + 1 to result, the number of good starts for this right end. When the first loop is done, return result.

The main method runs both examples and prints the two "at most" counts for Example 1. Then it tries an array of one repeated value with k = 1, and a k larger than the number of different values.

Java
import java.util.HashMap;
import java.util.Map;

public class CountSubarraysWithKDifferentIntegers {

    public static int subarraysWithKDistinct(int[] nums, int k) {
        return atMost(nums, k) - atMost(nums, k - 1);   // exactly k = at most k - at most k-1
    }

    // Number of subarrays with at most k different values
    static int atMost(int[] nums, int k) {
        Map<Integer, Integer> count = new HashMap<>();
        int left = 0;
        int result = 0;
        for (int right = 0; right < nums.length; right++) {
            count.merge(nums[right], 1, Integer::sum);
            while (count.size() > k) {
                if (count.merge(nums[left], -1, Integer::sum) == 0) {
                    count.remove(nums[left]);   // last copy left the window
                }
                left++;
            }
            result += right - left + 1;       // every start in left..right works for this end
        }
        return result;
    }

    public static void main(String[] args) {
        int[] example1 = {1, 2, 1, 2, 3};
        System.out.println(subarraysWithKDistinct(example1, 2));
        System.out.println(subarraysWithKDistinct(new int[] {1, 2, 1, 3, 4}, 3));
        System.out.println(atMost(example1, 2) + " - " + atMost(example1, 1));
        System.out.println(subarraysWithKDistinct(new int[] {5, 5, 5}, 1));
        System.out.println(subarraysWithKDistinct(new int[] {1, 2}, 3));
    }
}

Running it prints:

Output
7
3
12 - 5
6
0

The 7 and the 3 match the two examples. The third line shows where the 7 comes from: 12 subarrays of [1, 2, 1, 2, 3] hold at most 2 values, 5 hold at most 1, and 12 - 5 = 7.

The 6 comes from [5, 5, 5] with k = 1. Every one of its six subarrays holds only the value 5, so all of them count. The last line is 0 because [1, 2] has only two different values, so no subarray can hold three. Both "at most" counts there take in all three subarrays, and 3 - 3 = 0.

The line count.remove(nums[left]) is easy to leave out, but it matters. Without it, a value that has left the window keeps its key with a count of 0, so count.size() never drops. The second loop then moves left past the end of the array. For Example 1 the program stops with ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5.

Complexity

The work is two runs of the sliding window, one for k and one for k - 1.

  • Time: O(n), for an array of n numbers, because in each run right and left only move forward, so each number enters and leaves the window at most once. Each map update takes constant time on average.
  • Space: O(k). The map holds one key per different value in the window, and the window never keeps more than k + 1 different values.

The "at most k different values" window on its own is the subject of Longest Substring with At Most K Distinct Characters.