Subarrays with K Different Integers
Count the subarrays of an array that hold exactly k different values.
You are given an array of integers numsk[2, 1, 2][1, 2, 1, 2, 3]k
Example 1
Output: 7
Explanation: [1, 2], [2, 1], [1, 2], [2, 3], [1, 2, 1], [2, 1, 2], [1, 2, 1, 2].
Example 2
Output: 3
Explanation: [1, 2, 1, 3], [2, 1, 3], [1, 3, 4].
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]
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 blue box marks the right end, index 3. Starting there gives [2][1, 2]
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 kkk - 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 kk
Counting subarrays with at most k values
For each right end, how do we find the leftmost start that still has at most k
A faster way keeps a marker, leftrightrightleftleftrightkleftrightright - left + 1right
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 HashMaprightleft
From "at most" to "exactly"
How do two counts give the answer? Run the window count once with kk - 1kleftright
Java Solution
The method subarraysWithKDistinct
- First, call the helper
twice, withatMost and withk , and return the first result minus the second.k - 1 - Inside
, create the mapatMost , from value to how often it appears in the window. Setcount andleft to 0.result - A loop moves
from the first index to the last. At each step,right adds 1 to the count of the new number, or stores 1 if the value is new.count.merge(nums[right], 1, Integer::sum) - Inside, a second loop shrinks the window while
is more thancount.size() . It lowers the count ofk by one, removes that value from the map when its count reaches 0, and movesnums[left] one place right.left - Add
toright - left + 1 , the number of good starts for this right end. When the first loop is done, returnresult .result
The maink
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:
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]
The 6 comes from [5, 5, 5][1, 2]
The line count.remove(nums[left])count.size()leftArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Complexity
The work is two runs of the sliding window, one for kk - 1
- Time: O(n), for an array of n numbers, because in each run
andright only move forward, so each number enters and leaves the window at most once. Each map update takes constant time on average.left - 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