VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-minimum-subarray-length-to-reduce-frequency/

⇱ Find minimum subarray length to reduce frequency - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find minimum subarray length to reduce frequency

Last Updated : 23 Jul, 2025

Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k.

Examples:

Input: n = 4, arr[] = {3, 1, 3, 6}, k = 1
Output: 1
Explanation:  We can see that only 3 is having frequency 2 that is greater than k. So we can remove the 3 at the start of the array to that frequency of all elements become less than or equal to k. Thus the minimum length of the subarray to be removed is 1.

Input: n = 6, arr[] = {1, 2, 3, 3, 2, 1}, k = 1
Output: 3
Explanation: We Can remove the subarray {1, 2, 3} which is the minimum possible length subarray after being removed making the frequency of remaining elements less than or equal to k. 

Approach: This can be solved with the following idea:

This problem can be solved usingBinary Search and Sliding Window Technique.

Below are the steps involved in the implementation of the code:

  • Create a Hash Table to store the frequency of the elements of the given array.
  • Create a variable cnt to store the count of numbers to be removed for satisfying the condition that the frequency of remaining elements after removing the subarray becomes less than or equal to k.
  • Store the frequency of the array elements in the Hash table.
  • If the frequency of an element becomes greater than k then increment cnt.
  • Now the subarray size lies in the range [0, n] where n is the array length. So we can apply binary search to it.
  • Initialize the answer as n.
  • Find the mid element on every iteration of binary search and create a window of size mid and check if it is possible that removing this window size from the array can make cnt equal to zero.
  • If it is possible update the answer as a minimum of answer and mid and now reduce the search space to [left, mid-1] to find if a smaller length is possible.
  • If it is not possible then reduce the search space to [mid+1, r] to find for larger length than mid.
  • After the end of the binary search, we will get the required answer.

Below is the implementation of the above approach:


Output
1

Time Complexity: O(N*logN)
Auxiliary Space: O(N)

Comment
Article Tags: