Subarrays with K Different Integers
Problem
You are given an integer array nums and an integer k. Count the contiguous subarrays in which the number of distinct values is exactly k. Subarrays at different positions are counted separately even if their contents are identical.
numshas between 1 and 20,000 elements; values are positive integers with no particular upper bound.kis between 1 and the length ofnums.
Examples
nums = [4, 7, 4, 7, 9], k = 2→7. They are[4,7],[7,4],[4,7],[7,9],[4,7,4],[7,4,7],[4,7,4,7].nums = [3, 6, 3, 8, 1], k = 3→3.[3,6,3,8],[6,3,8],[3,8,1].nums = [9, 9, 9], k = 1→6. Every subarray of a constant array has exactly one distinct value: 3 of length 1, 2 of length 2, 1 of length 3.
Hints
- Try a window that keeps "exactly k distinct". Does shrinking a valid window always keep it valid? What goes wrong?
- "At most k distinct" does shrink cleanly. How would you count subarrays satisfying that in one pass?
- Answer = count(at most k) - count(at most k - 1). Each is a standard variable window where every right endpoint contributes
hi - lo + 1subarrays.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.