Permutation of first N natural numbers having given array as the prefix maximum array | Python3 program for the above approach ; Function to check if the maximum prefix array of ans [ ] is equal to array arr [ ] ; Initialize a variable , Max ; Traverse the array , ans [ ] ; Store the maximum value upto index i ; If it is not equal to a [ i ] , then return false ; Otherwise return false ; Function to find the permutation of the array whose prefix maximum array is same as the given array a [ ] ; Stores the required permutation ; Stores the index of first occurrence of elements ; Traverse the array a [ ] ; If a [ i ] is not present in um , then store it in um ; Update the ans [ i ] to a [ i ] ; Stores the unvisited numbers ; Fill the array , v [ ] ; Store the index ; Traverse the array , ans [ ] ; Fill v [ j ] at places where ans [ i ] is 0 ; Check if the current permutation maximum prefix array is same as the given array a [ ] ; If true , the print the permutation ; Otherwise , print - 1 ; Driver Code ; Function Call
import sys NEW_LINE def checkPermutation ( ans , a , n ) : NEW_LINE INDENT Max = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Max = max ( Max , ans [ i ] ) NEW_LINE if ( Max != a [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findPermutation ( a , n ) : NEW_LINE INDENT ans = [ 0 ] * n NEW_LINE um = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] not in um ) : NEW_LINE INDENT ans [ i ] = a [ i ] NEW_LINE um [ a [ i ] ] = i NEW_LINE DEDENT DEDENT v = [ ] NEW_LINE j = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i not in um ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ans [ i ] == 0 ) : NEW_LINE INDENT ans [ i ] = v [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT if ( checkPermutation ( ans , a , n ) ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 5 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE findPermutation ( arr , N ) NEW_LINE DEDENT