Related Articles

# Lexicographically smallest permutation of [1, N] based on given Binary string

• Last Updated : 13 Sep, 2021

Given a binary string S of size (N – 1), the task is to find the lexicographically smallest permutation P of the first N natural numbers such that for every index i, if S[i] equals ‘0‘ then P[i + 1] must be greater than P[i] and if S[i] equals ‘1‘ then P[i + 1] must be less than P[i].

Examples:

Input: N = 7, S = 100101
Output: 2 1 3 5 4 7 6
Explanation:
Consider the permutation as {2, 1, 3, 5, 4, 7, 6} that satisfy the given criteria as:
For index 0, S = 1, P < P, i.e. 1 < 2
For index 1, S = 0, P < P, i.e. 3 > 1
For index 2, S = 0, P < P, i.e. 5 > 3
For index 3, S = 1, P < P, i.e. 4 < 5
For index 4, S = 0, P < P, i.e. 7 > 4
For index 5, S = 1, P < P, i.e. 6 < 7

Input: N = 4, S = 000
Output: 1 2 3 4

Approach: The given problem can be solved by using the Greedy Approach by using smaller numbers at lower indices as much as possible will create the lexicographically smallest permutations. Follow the steps below to solve the problem:

• Initialize an array, say ans[] of size N that stores the resultant permutation.
• Traverse the given string S and perform the following steps:
• If the value of S[i] equals ‘0‘ then assign the number greater than the last assigned number.
• Otherwise, assign the smallest number which is larger than all currently used numbers.
• After completing the above steps, print the resultant permutation formed in the array ans[].

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to generate the lexicographically``// smallest permutation according to the``// given criteria``void` `constructPermutation(string S, ``int` `N)``{``    ``// Stores the resultant permutation``    ``int` `ans[N];` `    ``// Initialize the first elements to 1``    ``ans = 1;` `    ``// Traverse the given string S``    ``for` `(``int` `i = 1; i < N; ++i) {``        ``if` `(S[i - 1] == ``'0'``) {` `            ``// Number greater than last``            ``// number``            ``ans[i] = i + 1;``        ``}``        ``else` `{``            ``// Number equal to the last``            ``// number``            ``ans[i] = ans[i - 1];``        ``}` `        ``// Correct all numbers to the left``        ``// of the current index``        ``for` `(``int` `j = 0; j < i; ++j) {``            ``if` `(ans[j] >= ans[i]) {``                ``ans[j]++;``            ``}``        ``}``    ``}` `    ``// Printing the permutation``    ``for` `(``int` `i = 0; i < N; i++) {``        ``cout << ans[i];``        ``if` `(i != N - 1) {``            ``cout << ``" "``;``        ``}``    ``}``}` `// Driver Code``int` `main()``{``    ``string S = ``"100101"``;``    ``constructPermutation(S, S.length() + 1);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG {` `    ``// Function to generate the lexicographically``    ``// smallest permutation according to the``    ``// given criteria``    ``static` `void` `constructPermutation(String S, ``int` `N)``    ``{``      ` `        ``// Stores the resultant permutation``        ``int``[] ans = ``new` `int``[N];` `        ``// Initialize the first elements to 1``        ``ans[``0``] = ``1``;` `        ``// Traverse the given string S``        ``for` `(``int` `i = ``1``; i < N; ++i) {``            ``if` `(S.charAt(i - ``1``) == ``'0'``) {` `                ``// Number greater than last``                ``// number``                ``ans[i] = i + ``1``;``            ``}``            ``else` `{``                ``// Number equal to the last``                ``// number``                ``ans[i] = ans[i - ``1``];``            ``}` `            ``// Correct all numbers to the left``            ``// of the current index``            ``for` `(``int` `j = ``0``; j < i; ++j) {``                ``if` `(ans[j] >= ans[i]) {``                    ``ans[j]++;``                ``}``            ``}``        ``}` `        ``// Printing the permutation``        ``for` `(``int` `i = ``0``; i < N; i++) {``            ``System.out.print(ans[i]);``            ``if` `(i != N - ``1``) {``                ``System.out.print(``" "``);``            ``}``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args) {``        ` `        ``String S = ``"100101"``;``        ``constructPermutation(S, S.length() + ``1``);``    ``}``}` `// This code is contributed by code_hunt.`

## Python3

 `# Python Program to implement``# the above approach` `# Function to generate the lexicographically``# smallest permutation according to the``# given criteria``def` `constructPermutation(S, N):``  ` `    ``# Stores the resultant permutation``    ``ans ``=` `[``0``] ``*` `N` `    ``# Initialize the first elements to 1``    ``ans[``0``] ``=` `1` `    ``# Traverse the given string S``    ``for` `i ``in` `range``(``1``, N):``        ``if` `(S[i ``-` `1``] ``=``=` `'0'``):` `            ``# Number greater than last``            ``# number``            ``ans[i] ``=` `i ``+` `1``        ``else` `:``            ``# Number equal to the last``            ``# number``            ``ans[i] ``=` `ans[i ``-` `1``]``        `  `        ``# Correct all numbers to the left``        ``# of the current index``        ``for` `j ``in` `range``(i):``            ``if` `(ans[j] >``=` `ans[i]):``                ``ans[j] ``+``=` `1``           ` `    ``# Printing the permutation``    ``for` `i ``in` `range``(N):``        ``print``(ans[i], end``=``"")``        ``if` `(i !``=` `N ``-` `1``):``            ``print``(``" "``, end``=``"")``        ` `# Driver Code``S ``=` `"100101"``constructPermutation(S, ``len``(S) ``+` `1``)` `# This code is contributed by Saurabh Jaiswal`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG {` `    ``// Function to generate the lexicographically``    ``// smallest permutation according to the``    ``// given criteria``    ``static` `void` `constructPermutation(``string` `S, ``int` `N)``    ``{``      ` `        ``// Stores the resultant permutation``        ``int``[] ans = ``new` `int``[N];` `        ``// Initialize the first elements to 1``        ``ans = 1;` `        ``// Traverse the given string S``        ``for` `(``int` `i = 1; i < N; ++i) {``            ``if` `(S[i - 1] == ``'0'``) {` `                ``// Number greater than last``                ``// number``                ``ans[i] = i + 1;``            ``}``            ``else` `{``                ``// Number equal to the last``                ``// number``                ``ans[i] = ans[i - 1];``            ``}` `            ``// Correct all numbers to the left``            ``// of the current index``            ``for` `(``int` `j = 0; j < i; ++j) {``                ``if` `(ans[j] >= ans[i]) {``                    ``ans[j]++;``                ``}``            ``}``        ``}` `        ``// Printing the permutation``        ``for` `(``int` `i = 0; i < N; i++) {``            ``Console.Write(ans[i]);``            ``if` `(i != N - 1) {``                ``Console.Write(``" "``);``            ``}``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``string` `S = ``"100101"``;``        ``constructPermutation(S, S.Length + 1);``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``
Output:
`2 1 3 5 4 7 6`

Time Complexity: O(N2)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up