Lexicographically smallest permutation number up to K having given array as a subsequence | C # program for the above approach ; 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 Int32 . MaxValue 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 conthe 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
using System ; using System . Collections ; class GFG { static void findPermutation ( int K , ArrayList arr ) { ArrayList missing = new ArrayList ( ) ; bool [ ] visited = new bool [ K + 1 ] ; for ( int i = 0 ; i < arr . Count ; i ++ ) { visited [ ( int ) arr [ i ] ] = true ; } for ( int i = 1 ; i <= K ; i ++ ) { if ( ! visited [ i ] ) { missing . Add ( i ) ; } } arr . Add ( Int32 . MaxValue ) ; missing . Add ( Int32 . MaxValue ) ; int p1 = 0 ; int p2 = 0 ; ArrayList ans = new ArrayList ( ) ; while ( ans . Count < K ) { if ( ( int ) arr [ p1 ] < ( int ) missing [ p2 ] ) { ans . Add ( arr [ p1 ] ) ; p1 ++ ; } else { ans . Add ( missing [ p2 ] ) ; p2 ++ ; } } for ( int i = 0 ; i < K ; i ++ ) { Console . Write ( ans [ i ] + " ▁ " ) ; } } public static void Main ( ) { int K = 7 ; int [ ] a = { 6 , 4 , 2 , 1 } ; ArrayList arr = new ArrayList ( a ) ; findPermutation ( K , arr ) ; } }