Length of Longest Subarray With at Most K Frequency
Problem Statement
You are given an integer array nums and a number k.
Call a subarray good if no value appears more than k times inside it.
Return the length of the longest good subarray.
An integer array nums and an integer k.
One integer: the length of the longest contiguous subarray in which every value appears at most k times.
[1, 2, 3, 1, 2, 3] has each value exactly twice. Adding one more element on either side would make some value appear 3 times.
Any 3 neighbours contain a repeated value, so the best is a pair like [1, 2].
Four 5's are allowed, five are not.
- • 1 ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^9
- • 1 ≤ k ≤ nums.length
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, grow right with a fresh map until some count exceeds k
Grow right; while the entering value's count > k, shrink left
Try every start. Grow the end one element at a time with a fresh count map. The moment the new element's count becomes k + 1, stop for this start. Keep the longest length seen.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.