#992

Subarrays with K Different Integers

Hard atMost(k) − atMost(k−1)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count subarrays that contain exactly k distinct integers.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count subarrays with exactly k distinct numbers.

Why this works: same trick: exactly k = atMost(k) - atMost(k-1).

Example: [1, 2, 1, 2, 3], k = 2

atMost(2) = 12, atMost(1) = 5answer 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Trying to count exactly-k windows directly with one window — you miss subarrays that start in the middle of a run.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Sliding Window
🎬 Episode 10: video coming soon