LeetCode solutions

3225. Length of Longest Subarray With at Most K Frequency

My accepted Python solution to LeetCode problem 3225, Length of Longest Subarray With at Most K Frequency, running in 306ms.

  • Difficulty: Medium
  • Python
  • Runtime 306ms
  • Memory 33.5MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 306ms, memory 33.5MB, accepted 2026-01-02.

python
class Solution:
    def maxSubarrayLength(self, nums: List[int], k: int) -> int:
        from collections import defaultdict
        
        count = defaultdict(int)
        left = 0
        result = 0
        
        for right in range(len(nums)):
            count[nums[right]] += 1
            
            while count[nums[right]] > k:
                count[nums[left]] -= 1
                left += 1
            
            result = max(result, right - left + 1)
        
        return result

Source