⚡Flashcard Drill➔
NeetCode #249LC-2958MediumSliding Window
← Back to All Problems

#249 · #2958 · Length of Longest Subarray With at Most K Frequency(最多 K 个重复元素的最长子数组)

📌 Problem Statement & Constraints

Given an array of integers nums and an integer k, return the length of the longest subarray where the frequency of each element is at most k. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^9, 1 <= k <= nums.length.

💡 Core Algorithmic Approaches

  1. Maintain a window whose every element's frequency is at most k.
  2. When the entering element's frequency exceeds k, shrink from the left until it is back within budget.
  3. The window length is the candidate answer.
  4. Only the entering element's count can newly violate the constraint, so the shrink loop condition can be checked against that single element.

💻 Benchmark Python3 Implementation

class Solution:
    def maxSubarrayLength(self, nums: List[int], k: int) -> int:
        from collections import defaultdict
        cnt = defaultdict(int)
        l = 0
        best = 0
        for r, x in enumerate(nums):
            cnt[x] += 1
            while cnt[x] > k:          # only the entering element can violate
                cnt[nums[l]] -= 1
                l += 1
            best = max(best, r - l + 1)
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each element enters and leaves the window at most once.
💾 Space Complexity
O(n) for the frequency map in the worst case.

⚠️ Interview Pitfalls & Follow-ups

  • Checking all frequencies in the shrink condition: only the entering element's count can newly exceed k, so checking cnt[x] alone suffices and keeps the loop O(1) per step.
  • Shrinking until cnt[x] == k: the condition is cnt[x] > k, so the loop must run while it exceeds k.
  • Deleting zero-count keys: unnecessary here, since the constraint is per-element rather than on the number of distinct values.
  • Using a set: multiplicities are essential, so a count map is required.
⚡
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。一个元素 x 在子数组中 频数 指的是 x 在子数组中出现的次数。请你找出 nums 中每一个元素的频数都不超过 k 的 最长 子数组,并返回它的长度。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9;1 ≤ k ≤ nums.length。

核心要点

  • 滑动窗口 + 频次计数(标准解) :维护窗口内各元素的出现次数。当某个元素的频次超过 k 时,收缩左边界直到满足条件。
  • 收缩的优化 :由于只有新加入的元素可能导致超限,因此只需判断新元素 cnt[x] &gt; k 即可(收缩过程中其他元素的频次只会减少)。
  • 为什么只需判断 cnt[x] :加入 x 之前窗口是合法的,因此只有 x 的频次可能超标。
  • 复杂度 :O(n) 时间、O(n) 空间。

常见陷阱

  • 收缩时用 while any(v &gt; k for v in cnt.values()) :每次是 O(不同值数),整体可能退化为 O(n²)。只需判断 cnt[x] 。
  • 收缩条件写成 cnt[x] &gt;= k :题目允许「不超过 k」,应写 &gt; k 。
  • 不删除零计数键 :本题的判定依赖 cnt[x] 而非 len(cnt) ,因此不删除也不影响正确性,但会占用更多内存。
  • 误以为要限制所有元素的频次之和 :限制的是 每个 元素的频次,各自独立。

参考实现

from collections import defaultdict

class Solution:
    def maxSubarrayLength(self, nums: list[int], k: int) -> int:
        cnt = defaultdict(int)
        l = 0
        best = 0
        for r, x in enumerate(nums):
            cnt[x] += 1
            # 只有 x 的频次可能超标
            while cnt[x] > k:
                cnt[nums[l]] -= 1
                l += 1
            if r - l + 1 > best:
                best = r - l + 1
        return best