Remove array elements to reduce frequency of each array element to at most K | Function to remove array elements such that frequency of each distinct array element is at most K ; Base Case ; Stores index of array element by removing the array element such that the frequency of array elements is at most K ; Traverse the array ; If j < k or arr [ i ] > arr [ j - k ] ; Update arr [ j ] ; Remove array elements ; Function to print the array ; Traverse the array ; Utility Function to remove array elements such that frequency of each distinct array element is at most K ; Print updated array ; Driver Code
def RemoveElemArr ( arr , n , k ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return arr NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( j < k or arr [ i ] > arr [ j - k ] ) : NEW_LINE INDENT arr [ j ] , j = arr [ i ] , j + 1 NEW_LINE DEDENT DEDENT while ( len ( arr ) > j ) : NEW_LINE INDENT del arr [ - 1 ] NEW_LINE DEDENT return arr NEW_LINE DEDENT def printArray ( arr ) : NEW_LINE INDENT for i in arr : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT def UtilRemov ( arr , n , k ) : NEW_LINE INDENT arr = RemoveElemArr ( arr , n , k ) NEW_LINE printArray ( arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE UtilRemov ( arr , n , k ) NEW_LINE DEDENT