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
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 306ms, memory 33.5MB, accepted 2026-01-02.
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