Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums and an integer k.
The frequency of an element x is the number of times it occurs in an array.
An array is called good if the frequency of each element in this array is less than or equal to k.
Return the length of the longest good subarray of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,3,1,2,3,1,2], k = 2 Output: 6 Explanation: The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6.
Example 2:
Input: nums = [1,2,1,2,1,2,1,2], k = 1 Output: 2 Explanation: The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. It can be shown that there are no good subarrays with length more than 2.
Example 3:
Input: nums = [5,5,5,5,5,5,5], k = 4 Output: 4 Explanation: The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. It can be shown that there are no good subarrays with length more than 4.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= k <= nums.lengthProblem summary: You are given an integer array nums and an integer k. The frequency of an element x is the number of times it occurs in an array. An array is called good if the frequency of each element in this array is less than or equal to k. Return the length of the longest good subarray of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
[1,2,3,1,2,3,1,2] 2
[1,2,1,2,1,2,1,2] 1
[5,5,5,5,5,5,5] 4
longest-substring-with-at-least-k-repeating-characters)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2958: Length of Longest Subarray With at Most K Frequency
class Solution {
public int maxSubarrayLength(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
int ans = 0;
for (int i = 0, j = 0; i < nums.length; ++i) {
cnt.merge(nums[i], 1, Integer::sum);
while (cnt.get(nums[i]) > k) {
cnt.merge(nums[j++], -1, Integer::sum);
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}
}
// Accepted solution for LeetCode #2958: Length of Longest Subarray With at Most K Frequency
func maxSubarrayLength(nums []int, k int) (ans int) {
cnt := map[int]int{}
for i, j, n := 0, 0, len(nums); i < n; i++ {
cnt[nums[i]]++
for ; cnt[nums[i]] > k; j++ {
cnt[nums[j]]--
}
ans = max(ans, i-j+1)
}
return
}
# Accepted solution for LeetCode #2958: Length of Longest Subarray With at Most K Frequency
class Solution:
def maxSubarrayLength(self, nums: List[int], k: int) -> int:
cnt = defaultdict(int)
ans = j = 0
for i, x in enumerate(nums):
cnt[x] += 1
while cnt[x] > k:
cnt[nums[j]] -= 1
j += 1
ans = max(ans, i - j + 1)
return ans
// Accepted solution for LeetCode #2958: Length of Longest Subarray With at Most K Frequency
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2958: Length of Longest Subarray With at Most K Frequency
// class Solution {
// public int maxSubarrayLength(int[] nums, int k) {
// Map<Integer, Integer> cnt = new HashMap<>();
// int ans = 0;
// for (int i = 0, j = 0; i < nums.length; ++i) {
// cnt.merge(nums[i], 1, Integer::sum);
// while (cnt.get(nums[i]) > k) {
// cnt.merge(nums[j++], -1, Integer::sum);
// }
// ans = Math.max(ans, i - j + 1);
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2958: Length of Longest Subarray With at Most K Frequency
function maxSubarrayLength(nums: number[], k: number): number {
const cnt: Map<number, number> = new Map();
let ans = 0;
for (let i = 0, j = 0; i < nums.length; ++i) {
cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1);
for (; cnt.get(nums[i])! > k; ++j) {
cnt.set(nums[j], cnt.get(nums[j])! - 1);
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.