Check if given array can be rearranged such that mean is equal to median | Function to return true or false if size of array is odd ; To prevent overflow ; If element is greater than mid , then it can only be present in right subarray ; If element is smaller than mid , then it can only be present in left subarray ; Else the element is present at the middle then return 1 ; when element is not present in array then return 0 ; Function to return true or false if size of array is even ; Calculating Candidate Median ; If Candidate Median if greater than Mean then decrement j ; If Candidate Median if less than Mean then increment i ; If Candidate Median if equal to Mean then return 1 ; when No candidate found for mean ; Function to return true if Mean can be equal to any candidate median otherwise return false ; Calculating Mean ; If N is Odd ; If N is even ; Driver Code
def binarySearch ( arr , size , key ) : NEW_LINE INDENT low = 0 NEW_LINE high = size - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( key > arr [ mid ] ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT elif ( key < arr [ mid ] ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def twoPointers ( arr , N , mean ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT temp = ( arr [ i ] + arr [ j ] ) / 2 NEW_LINE if ( temp > mean ) : NEW_LINE INDENT j = j - 1 NEW_LINE DEDENT elif ( temp < mean ) : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def checkArray ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT mean = sum / N NEW_LINE if ( N & 1 ) : NEW_LINE INDENT return binarySearch ( arr , N , mean ) NEW_LINE DEDENT else : NEW_LINE INDENT return twoPointers ( arr , N , mean ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1.0 , 3.0 , 6.0 , 9.0 , 12.0 , 32.0 ] NEW_LINE N = len ( arr ) NEW_LINE if ( checkArray ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT