HardEditorial · 8 minGenerated by the editor · Sep 30
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Intuitionturning exactly k into two easier at-most questions
A window with exactly k distinct values is difficult to maintain directly: when it has too few values, moving either boundary might create the missing value, and when it has too many, several left positions may become valid after shrinking. The useful reformulation is to count windows with at most k distinct values, then remove the windows with at most k - 1 distinct values.
For a fixed right endpoint, keep the left endpoint as far left as possible while the window contains at most k distinct values. Every start from that left endpoint through right also forms a valid at-most-k window, because removing elements cannot introduce a new distinct value. Therefore this right endpoint contributes right - left + 1 windows. Subtracting the same count with limit k - 1 leaves exactly the windows whose distinct count is k.
The maintained boundary makes all valid starts for one right endpoint form a continuous range.
Approachone helper counts at most k, and subtraction enforces exactly k
1Define atMostKDistinct(nums, limit) to count subarrays containing no more than limit distinct values, because exactly k can be expressed as at most k minus at most k - 1.
2Return 0 immediately when limit is 0, because a non-empty subarray cannot contain zero distinct integers and this also avoids treating the helper's budget as a normal window.
3Scan right from left to right and increment the frequency of nums[right]. Decrease the remaining distinct-value budget only when that value was absent from the current window; repeated values must not consume another unit.
4While the budget is negative, decrement the frequency of nums[left] and increase the budget when that value disappears completely, then move left forward. This restores the smallest window ending at right that has at most limit distinct values.
5Add right - left + 1 to the helper's count. Every start from left through right produces a subarray ending at right inside the valid window, and starts before left would contain too many distinct values.
6Return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1). Every subarray with fewer than k distinct values appears in both counts and cancels, while every subarray with exactly k appears only in the first count.
Complexitytwo scans, with the output count kept separate from working memory
MEASURE
BOUND
WHY
Time
O(n)
Each helper advances right exactly n times, and left also only moves forward, at most n times. The inner shrinking loop therefore performs at most n removals per helper, so two helper calls still give a linear bound.
Space
O(n) extra
The frequency map stores at most one entry per distinct value in the current window, which is O(n) in the worst case. The returned count is output rather than working memory, so it is excluded from this bound.
Here n is the length of nums. The two helper calls each process the same n elements.
Annotated solutionC++ · two at-most counts · complete judge-ready implementation
CPPThe helper counts at most a given number of distinct values; the public method subtracts the two limits.
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1);
}
private:
int atMostKDistinct(vector<int>& nums, int k) {
if (k == 0) {
return 0;
}
unordered_map<int, int> freq;
int left = 0;
int count = 0;
for (int right = 0; right < static_cast<int>(nums.size()); ++right) {
if (freq[nums[right]]++ == 0) {
--k;
}
while (k < 0) {
if (--freq[nums[left]] == 0) {
++k;
}
++left;
}
count += right - left + 1;
}
return count;
}
};
The key accounting line is count += right - left + 1. The helper does not choose one window for each right endpoint; it counts every valid start at once. The frequency decrement must increase the budget only when a value's count reaches zero, because removing one copy of a repeated value does not remove that value from the set of distinct keys.
Common mistakeswrong window boundaries and wrong subtraction both look plausible