Magicsheet logo

Length of Longest Subarray With at Most K Frequency

Medium
61.1%
Updated 6/1/2025

Length of Longest Subarray With at Most K Frequency

What is this problem about?

The "Length of Longest Subarray With at Most K Frequency interview question" involves finding the longest continuous segment of an array where no single element appears more than k times. This "Length of Longest Subarray With at Most K Frequency coding problem" is a classic variation of the sliding window challenge, focusing on frequency constraints within a dynamic range.

Why is this asked in interviews?

Companies like Google and TikTok use this problem to test a candidate's ability to apply the "Sliding Window interview pattern" efficiently. It evaluates your skills in managing window boundaries and using a "Hash Table interview pattern" to track element frequencies in real-time as the window moves.

Algorithmic pattern used

The Sliding Window (Two Pointers) approach is the most effective. You maintain a left and right pointer. As you move the right pointer, you increment the frequency of the current element in a hash map. If any element's frequency exceeds k, you shrink the window from the left until the frequency of the element at the right pointer is back to k. The maximum value of right - left + 1 during this process is your answer.

Example explanation

Array: [1, 2, 1, 2, 3], k = 1

  1. Right = 0: [1], freq={1:1}. Max Len = 1.
  2. Right = 1: [1, 2], freq={1:1, 2:1}. Max Len = 2.
  3. Right = 2: [1, 2, 1], freq={1:2, 2:1}. Frequency of '1' is > 1.
  4. Move Left to 1: [2, 1], freq={1:1, 2:1}. Frequency of '1' is now 1. Max Len = 2.
  5. Right = 3: [2, 1, 2], freq={1:1, 2:2}. Move left until freq of '2' is 1. Window: [1, 2]. Result: The longest subarray length is 2.

Common mistakes candidates make

  • Shrinking the window incorrectly: Not using a while loop to move the left pointer far enough.
  • Inefficient frequency checks: Iterating through the entire hash map to check for frequencies instead of only checking the element that was just added.
  • Using O(n^2) approach: Trying all possible subarrays instead of the O(n) sliding window.

Interview preparation tip

Mastering the sliding window technique is crucial for array and string problems. Remember the template: Expand with right, check condition, shrink with left, and update the result.

Similar Questions