We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard sliding window problem, graded against 7 test cases (4 of them hidden).
A moving window over a contiguous run, expanding and contracting to hold an invariant.
Reach for it when you see: "Longest/shortest contiguous subarray or substring satisfying X."
More Sliding Windowproblems →Counting windows with *exactly* k distinct values does not fit a single sliding window, because validity is not monotonic as the window grows. But *at most k* is monotonic: maintain a window with at most k distinct values, and for each right endpoint, every subarray ending at `right` and starting at or after `left` qualifies - that's `right - left + 1` subarrays.
Subtracting `atMost(k-1)` from `atMost(k)` removes the subarrays with fewer than k distinct values, leaving exactly k.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.