Lexicographically smallest permutation of [ 1 , N ] based on given Binary string | Function to generate the lexicographically smallest permutation according to the given criteria ; Stores the resultant permutation ; Initialize the first elements to 1 ; Traverse the given string S ; Number greater than last number ; Number equal to the last number ; Correct all numbers to the left of the current index ; Printing the permutation ; Driver Code
function constructPermutation ( S , N ) { let ans = new Array ( N ) ; ans [ 0 ] = 1 ; for ( let i = 1 ; i < N ; ++ i ) { if ( S [ i - 1 ] == ' ' ) { ans [ i ] = i + 1 ; } else { ans [ i ] = ans [ i - 1 ] ; } for ( let j = 0 ; j < i ; ++ j ) { if ( ans [ j ] >= ans [ i ] ) { ans [ j ] ++ ; } } } for ( let i = 0 ; i < N ; i ++ ) { document . write ( ans [ i ] ) ; if ( i != N - 1 ) { document . write ( " " ) ; } } } let S = " " ; constructPermutation ( S , S . length + 1 ) ;