🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →
Day 24 - Sliding WindowPractice QuestionsSubarrays with K Different Integers

Subarrays with K Different Integers hard

Description

Given an integer array nums and an integer k, return the number of good subarrays of nums. A good subarray is a contiguous subarray with exactly k different integers.

Examples

> Case 1:
    nums = [1, 2, 1, 2, 3],  k = 2
    Output: 7
    Explanation:
        [1, 2], [2, 1], [1, 2], [2, 3],
        [1, 2, 1], [2, 1, 2], [1, 2, 1, 2]
 
> Case 2:
    nums = [1, 2, 1, 3, 4],  k = 3
    Output: 3

Constraints

  • 1 <= nums.length <= 2 × 10^4
  • 1 <= nums[i], k <= nums.length

Why direct sliding window doesn’t work

Sliding window naturally answers “longest” / “shortest” / “first” / “at most K” questions. For “exactly K,” the window can drift past K back to K-1 and forward to K+1 — there’s no natural place to record a count of “exactly-K windows ending here.”

The clean indirection: solve “exactly K” as at most K minus at most K−1, both of which ARE clean sliding-window problems.

State design

Define:

atMost(K) = number of contiguous subarrays with at most K distinct integers.

Then:

exactly(K) = atMost(K) - atMost(K - 1)

For atMost(K):

  1. Shape: variable-size, longest-valid-style. State: frequency map.
  2. Shrink while: len(freq) > K.
  3. Count contribution: every valid window contributes r − l + 1 (every subarray ending at r and starting at >= l is valid).

Code

Time: O(n) — two linear passes plus a subtraction. Space: O(k).

Why r − l + 1 per valid window? When the window [l..r] is valid (at-most-K distinct), so is every smaller right-aligned window: [l..r], [l+1..r], …, [r..r]. That’s r − l + 1 subarrays ending at r. Sum across all r and you’ve counted every at-most-K subarray exactly once.

Analysis

  • Time: O(n).
  • Space: O(k).

Same skin (every “exactly K” with a monotone counting property)

  • Count Number of Nice SubarraysatMost(k) − atMost(k − 1) on count of odd integers.
  • Binary Subarrays With Sum — same trick on a binary sum.
  • Subarrays with K Different Integers (this problem) — the canonical example.

If you ever see “exactly K … in a contiguous subarray,” try at-most-K first. If the “at most” version is monotone, you’re done in 12 lines.