↓Skip to main content
  1. LeetCode/

LeetCode 2958: Length of Longest Subarray With at Most K Frequency

·1 min· ·
LeetCode Medium Sliding-Window Hash-Table 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: medium First Attempt: 2026-01-10

  • Submissions: Accepted (first try)

Approach
#

The same template as LeetCode 3090, with the limit k instead of 2 and integers instead of characters.

After adding x on the right, only x can exceed k, so shrink the left until it is back to k.

My Solution
#

class Solution:
    def maxSubarrayLength(self, nums: List[int], k: int) -> int:
        cnt = Counter()
        left = best = 0
        for right, x in enumerate(nums):
            cnt[x] += 1
            while cnt[x] > k:
                cnt[nums[left]] -= 1
                left += 1
            best = max(best, right - left + 1)
        return best

Complexity
#

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

Mistakes to Avoid
#

  • Writing the shrink condition on the left element: check the newly added x.

Interview Explanation
#

A longest-window slide where each number appears at most k times. After adding x on the right only x can exceed, so I shrink the left until x is back to k and track the longest length. Time O(n).

Related

LeetCode 2653: Sliding Subarray Beauty
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2653 note: values are only -50 to 50, so the fixed window keeps a count array, and each window accumulates upward from -50 to find the x-th smallest negative
LeetCode 3795: Minimum Subarray Length With Distinct Sum At Least K
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 3795 note: a shortest-window slide where each value counts once; track each value’s last position, and subtract the left value only if it was the last occurrence
LeetCode 2461: Maximum Sum of Distinct Subarrays With Length K
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2461 note: in a fixed window of length k, all values are distinct exactly when the number of distinct values equals k
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 2841: Maximum Sum of Almost Unique Subarray
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2841 note: a fixed window of length k keeps a sum and a count map; the number of distinct values is the map’s size, so delete keys that drop to zero
LeetCode 1248: Count Number of Nice Subarrays
·3 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 1248 note: “exactly k odd numbers” is not monotonic, so compute “at most k” minus “at most k - 1”; or use prefix sums with a hash map