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
function minimumSubarray ( arr , n , m ) { let mapu = new Array ( m + 1 ) . fill ( 0 ) ; let c = 0 ; for ( let i = 0 ; i < n ; i ++ ) { mapu [ arr [ i ] ] ++ ; if ( mapu [ arr [ i ] ] == ( n / m ) + 1 ) c ++ ; } if ( c == 0 ) return 0 ; let ans = n ; let l = 0 , r = 0 ; while ( r < n ) { if ( -- mapu [ arr [ r ] ] == ( n / m ) ) c -- ; if ( c == 0 ) { while ( l <= r && c == 0 ) { ans = Math . min ( ans , r - l + 1 ) ; if ( ++ mapu [ arr [ l ] ] > ( n / m ) ) c ++ ; l ++ ; } } r ++ ; } return ans ; } let arr = [ 1 , 1 , 2 , 1 , 1 , 2 ] ; let M = 2 ; let N = arr . length ; document . write ( minimumSubarray ( arr , N , M ) ) ;