Subarrays with K Different Integers solution explained
Subarrays with K Different Integers asks how many contiguous subarrays contain exactly k distinct values. Counting exactly k with one window is awkward, but counting at most k is easy: for each right edge, shrink the left edge until at most k distinct values remain, then every start in between is valid. So the answer is atMost(k) minus atMost(k - 1), two linear passes with a count map, O(n) time and O(k) space.
By Evin JohnPublished 7 min read
Restating the problem
Given an array of integers and a positive integer k, count the contiguous subarrays in which exactly k different values appear. A value repeated inside the slice still counts once toward the k. Slices are told apart by position, so two identical-looking slices at different places both count. The values themselves are just labels; nothing is added or compared by size.
| Values | k | Count | Notes |
|---|---|---|---|
[3, 1, 3, 2] | 2 | 4 | [3,1], [1,3], [3,1,3], [3,2] |
[5, 5, 5] | 1 | 6 | Every slice has one distinct value |
[4, 4, 7, 7, 4] | 2 | 8 | Repeats inside a slice do not add kinds |
[9, 8, 9, 8, 7] | 3 | 3 | Each must reach the 7 at the end |
[1, 2, 3] | 3 | 1 | Only the whole array |
[1, 2, 3] | 4 | 0 | Not enough kinds anywhere |
What makes it hard, and what is being tested
The natural sliding window finds the longest or shortest slice with a property. Here you need a count of all slices with exactly k kinds, and "exactly k" is not monotone: shrinking a slice can drop it to k - 1 kinds, and growing it can push it to k + 1. Interviewers want to see you turn the question into two monotone ones. They also like to ask why the prefix-sum trick used for counting odd numbers fails here: the number of distinct values in a slice is not the difference of two prefix quantities, because a value seen before the slice may also appear inside it.
Quadratic baseline
def exactly_k_brute(nums, k):
total = 0
for i in range(len(nums)):
kinds = set()
for j in range(i, len(nums)):
kinds.add(nums[j])
if len(kinds) > k:
break
if len(kinds) == k:
total += 1
return totalAt most k, minus at most k - 1
- Write a counter for at most kSlide a right edge across the array, adding each value to a count map.
- Shrink when there are too many kindsWhile the map has more than k keys, remove the leftmost value and delete its key at zero.
- Count the startsEvery start from the left edge to the right edge gives a slice with at most k kinds, so add
right - left + 1. - SubtractSlices with exactly k kinds are those with at most k minus those with at most k - 1.
def exactly_k(nums, k):
def at_most(limit):
if limit <= 0:
return 0
tally = {}
left = result = 0
for right, v in enumerate(nums):
tally[v] = tally.get(v, 0) + 1
while len(tally) > limit:
gone = nums[left]
tally[gone] -= 1
if tally[gone] == 0:
del tally[gone]
left += 1
result += right - left + 1
return result
return at_most(k) - at_most(k - 1)function exactlyK(nums, k) {
const atMost = (limit) => {
if (limit <= 0) return 0;
const tally = new Map();
let left = 0;
let result = 0;
for (let right = 0; right < nums.length; right++) {
const v = nums[right];
tally.set(v, (tally.get(v) || 0) + 1);
while (tally.size > limit) {
const gone = nums[left];
const rest = tally.get(gone) - 1;
if (rest === 0) tally.delete(gone);
else tally.set(gone, rest);
left++;
}
result += right - left + 1;
}
return result;
};
return atMost(k) - atMost(k - 1);
}Check it on [3, 1, 3, 2] with k = 2. At most 2 kinds: 1 + 2 + 3 + 2 = 8 slices. At most 1 kind: just the four single values, 4. The difference is 4, matching the table. The guard limit <= 0 returns 0, which is correct because no non-empty slice has zero kinds.
One pass with two left edges
You can fuse the two passes. Keep two left edges over the same right edge: far is the smallest start for which the window has at most k kinds, and near is the smallest start with at most k - 1 kinds. Starts from far up to near - 1 give exactly k kinds, so add near - far at each step. Each left edge has its own count map and only moves forward.
def exactly_k_one_pass(nums, k):
wide, narrow = {}, {}
far = near = total = 0
for v in nums:
wide[v] = wide.get(v, 0) + 1
narrow[v] = narrow.get(v, 0) + 1
while len(wide) > k:
u = nums[far]
wide[u] -= 1
if wide[u] == 0:
del wide[u]
far += 1
while len(narrow) > k - 1:
u = nums[near]
narrow[u] -= 1
if narrow[u] == 0:
del narrow[u]
near += 1
total += near - far
return totalThis version assumes k is at least 1, which the usual statement guarantees. With k = 1 the narrow map must stay empty, so near always moves past the right edge, and the count added is the length of the current run of one value, which is exactly right.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Every start with a set | O(n²) | O(k) |
| atMost(k) - atMost(k - 1) | O(n), two passes | O(k) |
| Two left edges, one pass | O(n) | O(k) |
If the values are known to lie in a small range such as 1 to n, arrays can replace the maps, which removes hashing from the constant factor.
Cases to cover
- k larger than the number of distinct values in the whole array: 0.
- k = 1 with long runs of one value, such as
[5, 5, 5]. - Every value different, where the count for k is n - k + 1.
- A value that leaves and re-enters the window, like the 4 in
[4, 4, 7, 7, 4]. - Negative values and zero as labels; nothing changes because values are only keys.
- An empty array: 0.
Where people go wrong
- Adding 1 per right edge instead of the number of valid starts.
- Leaving zero-count keys in the map, so
sizeoverstates the kinds. - Using the prefix-difference trick from odd counting, which double counts values seen on both sides of a start.
- Letting the at-most counter receive a negative limit (k = 0) without a guard: the shrink loop never stops and runs the left edge off the end of the array.
- Assuming the answer fits in 32 bits for long arrays; it can be about n²/2.
Explaining the idea
Fictional example
- Candidate
- Exactly k kinds isn't something I can maintain with one window, since shrinking might drop below k. But at most k is easy: dropping values from the left never adds kinds.
- Candidate
- For each right edge I shrink until at most k kinds remain, and then every start up to the right edge works, so I add the window length. Doing that for k and for k minus one and subtracting gives exactly k.
- Candidate
- Both are linear with a count map. If you want one pass, I can keep two left edges and add the gap between them.
Related problems
Count Number of Nice Subarrays uses the same subtraction for odd values and also allows a prefix map. The window that finds the longest slice instead of counting them is Longest Substring with At Most K Distinct Characters, and its special case for two kinds is the two-distinct version. Batch counting in a sorted sweep appears in 3Sum Smaller.
Rehearsing with Natively
In practice runs on Mac or Windows, Natively can read a counting problem like this from a screenshot and suggest the at-most subtraction with code, which you can check against your own brute force. The transcript of your mock interview lets you hear whether you explained why exactly k is not monotone before writing anything. More about an AI interview assistant.
Questions people ask
How do you count subarrays with exactly k distinct integers?
Count subarrays with at most k distinct values with a sliding window, do the same for k - 1, and subtract. Each pass is O(n) with a count map.
Why not use prefix sums as for odd counts?
The number of distinct values in a slice is not a difference of two prefix values, because a value can appear both before and inside the slice.
Can it be done in one pass?
Yes. Keep two left edges with their own count maps, one for at most k kinds and one for at most k - 1, and add the gap between them at each step.
What is the time complexity?
O(n) time and O(k) space for either version; the quadratic baseline grows every start with a set.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
