Distinct adjacent elements in an array | Python program to check if we can make neighbors distinct . ; dict used to count the frequency of each element occurring in the array ; In this loop we count the frequency of element through map m ; mx store the frequency of element which occurs most in array . ; In this loop we calculate the maximum frequency and store it in variable mx . ; By swapping we can adjust array only when the frequency of the element which occurs most is less than or equal to ( n + 1 ) / 2 . ; Driver Code
def distantAdjacentElement ( a , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] in m : NEW_LINE INDENT m [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT mx = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if mx < m [ a [ i ] ] : NEW_LINE INDENT mx = m [ a [ i ] ] NEW_LINE DEDENT DEDENT if mx > ( n + 1 ) // 2 : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 7 , 7 , 7 , 7 ] NEW_LINE n = len ( a ) NEW_LINE distantAdjacentElement ( a , n ) NEW_LINE DEDENT