Length of Longest Subarray With At Most K Frequency – Sliding Window Approach
Length of Longest Subarray With At Most K Frequency – Sliding Window Approach

Length of Longest Subarray With At Most K Frequency – Sliding Window Approach

Learn how to find the longest contiguous subarray where each element occurs at most K times using HashMap and sliding window.

36 views
0
0

Introduction

LeetCode 2958: Length of Longest Subarray With at Most K Frequency is an excellent problem to understand how sliding window with frequency counting works in arrays with duplicates.

The problem asks us to find the longest contiguous subarray such that no element occurs more than K times.

If you’d like to try solving the problem first, you can attempt it here:

Try the problem on LeetCode:

https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/


Problem Understanding

You are given:

  1. An integer array nums
  2. An integer k

A good subarray is defined as a subarray where the frequency of each element is ≤ k.

Goal: Return the length of the longest good subarray.


Examples:

Input: nums = [1,2,3,1,2,3,1,2], k = 2
Output: 6
Explanation: Longest good subarray = [1,2,3,1,2,3]

Input: nums = [1,2,1,2,1,2,1,2], k = 1
Output: 2
Explanation: Longest good subarray = [1,2]

Input: nums = [5,5,5,5,5,5,5], k = 4
Output: 4
Explanation: Longest good subarray = [5,5,5,5]

A naive approach would check all subarrays and count frequencies →

  1. Time Complexity: O(n²) → too slow for nums.length up to 10⁵


Key Idea: Sliding Window with Frequency Map

Instead of brute-force:

  1. Use a sliding window [i, j] to track the current subarray
  2. Use a HashMap mp to store the frequency of each element in the window
  3. Expand j by adding nums[j] to the map
  4. If mp.get(nums[j]) > k, shrink the window from the left (i) until mp.get(nums[j]) <= k
  5. At each step, update the maximum length of the valid window

Intuition:

  1. We allow each element to appear at most K times
  2. By shrinking the window whenever a frequency exceeds k, we always maintain a valid subarray
  3. Sliding window ensures linear traversal


Approach (Step-by-Step)

  1. Initialize i = 0, j = 0 → window pointers
  2. Initialize co = 0 → maximum length
  3. Initialize HashMap mp to store frequencies of elements in the window
  4. Iterate j from 0 to nums.length - 1:
  5. Increment frequency of nums[j] in mp
  6. While mp.get(nums[j]) > k:
  7. Shrink window from the left by decrementing mp[nums[i]] and incrementing i
  8. Update co = max(co, j - i + 1)
  9. Return co as the length of the longest good subarray


Implementation (Java)

class Solution {
public int maxSubarrayLength(int[] nums, int k) {
int i = 0, j = 0; // window pointers
int co = 0; // max length of good subarray
HashMap<Integer, Integer> mp = new HashMap<>(); // frequency map

while (j < nums.length) {
mp.put(nums[j], mp.getOrDefault(nums[j], 0) + 1);

// Shrink window until all frequencies <= k
while (mp.get(nums[j]) > k) {
mp.put(nums[i], mp.get(nums[i]) - 1);
i++;
}

co = Math.max(co, j - i + 1);
j++;
}

return co;
}
}


Dry Run Example

Input:

nums = [1,2,3,1,2,3,1,2], k = 2


Execution:

Window [i, j]Frequency Map mpValid?Max length co
[0,0] → [1]{1:1}Yes1
[0,1] → [1,2]{1:1,2:1}Yes2
[0,2] → [1,2,3]{1:1,2:1,3:1}Yes3
[0,3] → [1,2,3,1]{1:2,2:1,3:1}Yes4
[0,4] → [1,2,3,1,2]{1:2,2:2,3:1}Yes5
[0,5] → [1,2,3,1,2,3]{1:2,2:2,3:2}Yes6
[0,6] → [1,2,3,1,2,3,1]{1:3,2:2,3:2}No → shrink6


Output:

6


Complexity Analysis

  1. Time Complexity: O(n) → Each element enters and leaves the window at most once
  2. Space Complexity: O(n) → HashMap stores frequencies of elements in the window (worst-case all distinct)


Edge Cases Considered

  1. All elements occur ≤ k → entire array is valid
  2. All elements occur > k → max subarray length = k
  3. Single-element arrays → return 1 if k ≥ 1
  4. Large arrays up to 10⁵ elements → O(n) solution works efficiently


Sliding Window Pattern Importance

This problem demonstrates sliding window with frequency map, useful for:

  1. Subarrays with frequency constraints
  2. Longest subarray with limited duplicates
  3. Similar to "max consecutive ones with flips" and "fruit into baskets"

By mastering this approach, you can efficiently solve many array and subarray problems with constraints.


Conclusion

Using HashMap + sliding window, we reduce a naive O(n²) approach to O(n) while keeping the solution intuitive and easy to implement.

Understanding this pattern allows solving complex frequency-constrained subarray problems efficiently in interviews.

Ai Assistant Kas