Minimum length of the subarray required to be replaced to make frequency of array elements equal to N / M | 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
def minimumSubarray ( arr , n , m ) : NEW_LINE INDENT mapu = [ 0 for i in range ( m + 1 ) ] NEW_LINE c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mapu [ arr [ i ] ] += 1 NEW_LINE if ( mapu [ arr [ i ] ] == ( n // m ) + 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = n NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while ( r < n ) : NEW_LINE INDENT mapu [ arr [ r ] ] -= 1 NEW_LINE if ( mapu [ arr [ r ] ] == ( n // m ) ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT while ( l <= r and c == 0 ) : NEW_LINE INDENT ans = min ( ans , r - l + 1 ) NEW_LINE mapu [ arr [ l ] ] += 1 NEW_LINE if ( mapu [ arr [ l ] ] > ( n // m ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT r += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 1 , 2 ] NEW_LINE M = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( minimumSubarray ( arr , N , M ) ) NEW_LINE DEDENT