⚡Flashcard Drill➔
NeetCode #256LC-992HardSliding Window
← Back to All Problems

#256 · #992 · Subarrays with K Different Integers(K 个不同整数的子数组)

📌 Problem Statement & Constraints

Given an integer array nums and an integer k, return the number of good subarrays: contiguous subarrays with exactly k different integers. Constraints: 1 <= nums.length <= 2 * 10^4, 1 <= nums[i], k <= nums.length.

💡 Core Algorithmic Approaches

  1. The "exactly k" count decomposes as atMost(k) - atMost(k - 1).
  2. atMost(g) is a sliding window with at most g distinct values, contributing r - l + 1 subarrays per right endpoint.
  3. When shrinking, delete keys whose count reaches zero so the distinct count stays accurate.
  4. The answer is the difference of the two counts.

💻 Benchmark Python3 Implementation

class Solution:
    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
        from collections import defaultdict

        def atMost(g: int) -> int:
            if g <= 0:
                return 0
            cnt = defaultdict(int)
            l = 0
            res = 0
            for r, x in enumerate(nums):
                cnt[x] += 1
                while len(cnt) > g:    # too many distinct values
                    cnt[nums[l]] -= 1
                    if cnt[nums[l]] == 0:
                        del cnt[nums[l]]
                    l += 1
                res += r - l + 1
            return res

        return atMost(k) - atMost(k - 1)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): two linear passes, since each pointer moves monotonically within each call.
💾 Space Complexity
O(n) for the frequency maps.

⚠️ Interview Pitfalls & Follow-ups

  • Using one window with two left pointers: possible, but the two-pass formulation is far easier to get right.
  • Not deleting zero-count keys: len(cnt) would be wrong.
  • Forgetting the g <= 0 guard: atMost(0) must be 0, and the window logic would otherwise allow empty windows incorrectly.
  • Confusing "exactly k distinct" with "at most k distinct": the problem asks for exactly k.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

K 个不同整数的子数组

给定一个正整数数组 nums 和一个整数 k,返回 nums 中「 好子数组 」的数目。如果 nums 的某个子数组中 不同整数的个数恰好为 k ,则称 nums 的这个连续、不一定不同的子数组为「好子数组」。例如, [1,2,3,1,2] 中有 3 个不同的整数:1、2 以及 3。约束:1 ≤ nums.length ≤ 2 × 10^4;1 ≤ nums[i], k ≤ nums.length。

核心要点

  • 「恰好 k」= 「至多 k」−「至多 k−1」(标准解) :定义 atMost(kk) 为「不同整数个数 ≤ kk 的子数组数」,答案 = atMost(k) − atMost(k−1) 。
  • atMost 的滑动窗口 :维护窗口内各整数的计数;当不同整数数( len(cnt) )超过 kk 时收缩左边界。累加 r − l + 1 。
  • 为什么必须用「至多作差」 :因为窗口内不同整数数恰好为 k 时,左边界不唯一(相同整数可重复),无法直接计数。
  • 删除零计数键 : len(cnt) 表示不同整数数,因此收缩时计数降为 0 必须删除。

常见陷阱

  • 不删除零计数键 : len(cnt) 无法下降,while 无法退出或窗口被错误收缩。
  • atMost(k−1) 中 k = 1 时 : atMost(0) 应返回 0(不同整数数 ≤ 0 只能对应空窗口),本解中 len(cnt) &gt; 0 会立即收缩到空窗口, res += r − l + 1 中 r − l + 1 为 0,因此返回 0,正确。
  • 试图用「恰好 k」直接滑动 :左边界不唯一,会漏计或重复。
  • 用 len(set(nums[l:r+1])) 判不同整数数 :每次是 O(k),整体 O(n²)。

参考实现

from collections import defaultdict

class Solution:
    def subarraysWithKDistinct(self, nums: list[int], k: int) -> int:
        def atMost(kk: int) -> int:
            """不同整数个数 <= kk 的子数组数。"""
            cnt = defaultdict(int)
            l = 0
            res = 0
            for r, x in enumerate(nums):
                cnt[x] += 1
                while len(cnt) > kk:        # 不同整数过多 -> 收缩
                    cnt[nums[l]] -= 1
                    if cnt[nums[l]] == 0:
                        del cnt[nums[l]]
                    l += 1
                res += r - l + 1            # 左端点可取 l..r
            return res

        return atMost(k) - atMost(k - 1)