Minimum length of the subarray required to be replaced to make frequency of array elements equal to N / M | C ++ program for the above approach ; Function to find the minimum length of the subarray to be changed . ; Stores the frequencies of array elements ; Stores the number of array elements that are present more than N / M times ; Iterate over the range ; Increment the frequency ; If the frequency of all array elements are already N / M ; Stores the resultant length of the subarray ; The left and right pointers ; Iterate over the range ; If the current element is ; If the value of c is 0 , then find the possible answer ; Iterate over the range ; If the element at left is making it extra ; Update the left pointer ; Update the right pointer ; Return the resultant length ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSubarray ( vector < int > arr , int n , int m ) { vector < int > mapu ( m + 1 , 0 ) ; int c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mapu [ arr [ i ] ] ++ ; if ( mapu [ arr [ i ] ] == ( n / m ) + 1 ) c ++ ; } if ( c == 0 ) return 0 ; int ans = n ; int l = 0 , r = 0 ; while ( r < n ) { if ( -- mapu [ arr [ r ] ] == ( n / m ) ) c -- ; if ( c == 0 ) { while ( l <= r && c == 0 ) { ans = min ( ans , r - l + 1 ) ; if ( ++ mapu [ arr [ l ] ] > ( n / m ) ) c ++ ; l ++ ; } } r ++ ; } return ans ; } int main ( ) { vector < int > arr = { 1 , 1 , 2 , 1 , 1 , 2 } ; int M = 2 ; int N = arr . size ( ) ; cout << minimumSubarray ( arr , N , M ) ; return 0 ; }