Lexicographically smallest permutation number up to K having given array as a subsequence | Function to find the lexicographically smallest permutation such that the given array is a subsequence of it ; Stores the missing elements in arr in the range [ 1 , K ] ; Stores if the ith element is present in arr or not ; Loop to mark all integers present in the array as visited ; Loop to insert all the integers not visited into missing ; Append INT_MAX at end in order to prevent going out of bounds ; Pointer to the current element ; Pointer to the missing element ; Stores the required permutation ; Loop to construct the permutation using greedy approach ; If missing element is smaller that the current element insert missing element ; Insert current element ; Print the required Permutation ; Driver Code ; Function Call
const findPermutation = ( K , arr ) => { let missing = [ ] ; let visited = new Array ( K + 1 ) . fill ( 0 ) ; for ( let i = 0 ; i < arr . length ; i ++ ) { visited [ arr [ i ] ] = 1 ; } for ( let i = 1 ; i <= K ; i ++ ) { if ( ! visited [ i ] ) { missing . push ( i ) ; } } const INT_MAX = 2147483647 ; arr . push ( INT_MAX ) ; missing . push ( INT_MAX ) ; let p1 = 0 ; let p2 = 0 ; let ans = [ ] ; while ( ans . length < K ) { if ( arr [ p1 ] < missing [ p2 ] ) { ans . push ( arr [ p1 ] ) ; p1 ++ ; } else { ans . push ( missing [ p2 ] ) ; p2 ++ ; } } for ( let i = 0 ; i < K ; i ++ ) { document . write ( ` ${ ans [ i ] } ` ) ; } } let K = 7 ; let arr = [ 6 , 4 , 2 , 1 ] ; findPermutation ( K , arr ) ;