Number of possible permutations when absolute difference between number of elements to the right and left are given | Function to find the number of permutations possible of the original array to satisfy the given absolute differences ; To store the count of each a [ i ] in a map ; if n is odd ; check the count of each whether it satisfy the given criteria or not ; there is only 1 way for middle element . ; for others there are 2 ways . ; now find total ways ; When n is even . ; there will be no middle element so for each a [ i ] there will be 2 ways ; Driver Code
def totalways ( arr , n ) : NEW_LINE INDENT cnt = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ arr [ i ] ] = cnt . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT start , endd = 0 , n - 1 NEW_LINE for i in range ( start , endd + 1 , 2 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( cnt [ i ] != 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( cnt [ i ] != 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT ways = 1 NEW_LINE start = 2 NEW_LINE endd = n - 1 NEW_LINE for i in range ( start , endd + 1 , 2 ) : NEW_LINE INDENT ways = ways * 2 NEW_LINE DEDENT return ways NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT start = 1 NEW_LINE endd = n - 1 NEW_LINE for i in range ( 1 , endd + 1 , 2 ) : NEW_LINE INDENT if ( cnt [ i ] != 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT ways = 1 NEW_LINE for i in range ( start , endd + 1 , 2 ) : NEW_LINE INDENT ways = ways * 2 NEW_LINE DEDENT return ways NEW_LINE DEDENT DEDENT N = 5 NEW_LINE arr = [ 2 , 4 , 4 , 0 , 2 ] NEW_LINE print ( totalways ( arr , N ) ) NEW_LINE