↓Skip to main content
  1. LeetCode/

LeetCode 992: Subarrays with K Different Integers

·2 mins· ·
LeetCode Hard Sliding-Window Hash-Table Counting Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-01-21

  • Submissions: Accepted (first try)

Approach
#

“Exactly k distinct” is not monotonic, but “at most k distinct” is:

exactly k = at most k − at most k - 1

The “at most” count: shrink the left when there are too many kinds, and right - left + 1 valid subarrays end at right.

My Solution
#

My accepted version used the same extra trick as LeetCode 3306: with exactly k kinds, shrink away redundant repeats on the left, record them in extra, and add 1 + extra per right end, resetting extra when too many kinds force one out. Here it is in the more general at-most difference form:

class Solution:
    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
        def at_most(limit: int) -> int:
            cnt = Counter()
            left = count = 0
            for right, x in enumerate(nums):
                cnt[x] += 1
                while len(cnt) > limit:
                    y = nums[left]
                    cnt[y] -= 1
                    if cnt[y] == 0:
                        del cnt[y]
                    left += 1
                count += right - left + 1
            return count

        return at_most(k) - at_most(k - 1)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Delete keys whose count reaches zero, so len(cnt) is the number of kinds.

Interview Explanation
#

“Exactly k kinds” is not monotonic, so I compute “at most k” minus “at most k - 1”. Each at-most count is a sliding window that shrinks when there are too many kinds and adds right - left + 1 per right end. Both passes are O(n).

Related

LeetCode 2009: Minimum Number of Operations to Make Array Continuous
·2 mins
LeetCode Hard Sliding-Window Hash-Table Binary-Search Array
LeetCode 2009 note: the result is n consecutive integers; after deduplicating and sorting, a sliding window finds the most distinct values within a span of n - 1, and the rest must change
LeetCode 3679: Minimum Discards to Balance Inventory
·3 mins
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 note: the rule already decides what must be discarded, so simulate it; the length-w window counts only kept arrivals, and discarded ones must not be subtracted when they leave
LeetCode 3298: Count Substrings That Can Be Rearranged to Contain a String II
·2 mins
LeetCode Hard Sliding-Window Hash-Table String
LeetCode 3298 note: rearrangeable to start with word2 ⇔ every character count is at least word2’s; an “at least” counting window where meet tracks how many characters have reached their target
LeetCode 930: Binary Subarrays With Sum
·2 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 930 note: “sum exactly goal” = “sum at most goal” − “sum at most goal - 1”; or prefix sums with a hash map
LeetCode 2302: Count Subarrays With Score Less Than K
·2 mins
LeetCode Hard Sliding-Window Prefix-Sum Binary-Search Array
LeetCode 2302 note: score = sum × length with positive numbers grows with the window; shrink while the score is >= k, and right - left + 1 valid subarrays end at right
LeetCode 2968: Apply Operations to Maximize Frequency Score
·2 mins
LeetCode Hard Sliding-Window Sorting Prefix-Sum Binary-Search Array
LeetCode 2968 note: after sorting, the cheapest common target for a block is its median; prefix sums give the cost in O(1), and it grows with the window, so slide