VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-longest-subarray-having-at-most-k-frequency/

⇱ Length of Longest Subarray having at Most K Frequency - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of Longest Subarray having at Most K Frequency

Last Updated : 23 Jul, 2025

Given an integer array arr[]and an integer K, the task is to find the length of the longest subarray such that the frequency of each element is less than or equal to K.

Examples:

Input: arr[] = {10, 20, 30, 10, 20, 30, 10, 20}, K = 2
Output: 6
Explanation: The longest possible subarray is {10, 20, 30, 10, 20, 30} since the values 10, 20 and 30 occur at most twice in this subarray. Note that the subarrays {20, 30, 10, 20, 30, 10} and {30, 10, 20, 30, 10, 20} are also longest possible subarrays.

Input: arr[] = {5, 10, 5, 10, 5, 10}, K = 1
Output: 2
Explanation: The longest possible subarray is {5, 10} since the values 5 and 10 occur at most once in this subarray. Note that the subarray [10, 5] is also longest possible subarray.

Approach: To solve the problem, follow the below idea:

The problem can be solved using Two pointer technique. Start with two pointers l = 0 and r = 0 to mark the starting and ending of valid subarrays. Increment r to increase the length of the subarray and record the frequency of each element. If the frequency of current element becomes greater than K, then move the starting pointer l and decrement the frequency of arr[l] till the frequency of current element becomes <= K. Update the maximum length if the length of current array is greater than the maximum length.

Step-by-step algorithm:

  • Initialize two pointers, l and r, to mark the left and right boundaries of the current subarray.
  • Initialize an unordered_map to store the frequency of elements within the current subarray.
  • Iterate through the array from left to right using the right pointer r.
  • Increment the frequency of nums[r] in the map.
  • If the frequency of nums[r] exceeds k, we need to shrink the window from the left until the frequency new inserted element decrease by one.
  • Update the maximum length of the valid subarray if necessary.
  • Return the maximum length found.

Below is the implementation of the approach:


Output
2

Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(N)

Comment
Article Tags: