Subarrays with K Different Integers
Problem Statement
You are given an integer array nums and a number k.
Call a contiguous subarray good if it contains exactly k different values. For example, [1, 2, 3, 1, 2] has 3 different values: 1, 2 and 3.
Count the good subarrays.
An integer array nums and an integer k.
The number of contiguous subarrays with exactly k distinct values.
The good subarrays are [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2] and [1,2,1,2].
The good subarrays are [1,2,1,3], [2,1,3] and [1,3,4].
- • 1 ≤ nums.length ≤ 2 · 10^4
- • 1 ≤ nums[i] ≤ nums.length
- • 1 ≤ k ≤ nums.length
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Fix each start, grow the end with a count map, count when distinct = k
Two at-most-k-distinct windows; subtract
For every start, move the end right and keep a count of each value. Track how many different values there are. Count one whenever it equals k, and stop once it goes above k (it can never come back down for this start).
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.