Given a string str containing only characters 0, 1 and 2, you can swap any two adjacent (consecutive) characters 0 and 1 or any two adjacent (consecutive) characters 1 and 2. The task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times.
Input: str = “100210”
We can swap 0 and 1 OR we can swap 1 and 2. Swapping 0 and 2 is not allowed. All the swaps can happen for adjacent only.
Input: str = “2021”
Note that 0 and 2 cannot be swapped
Approach: You can print all the 1s together as 1 can be swapped with either of the other characters while 0 and 2 can not be swapped, so all the 0s and 2s will follow the same order as the original string.
Below is the implementation of the above approach:
- Generate permutations with only adjacent swaps allowed
- Minimum number of adjacent swaps to convert a string into its given anagram
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically smallest string of length N and sum K
- K-th lexicographically smallest unique substring of a given string
- Lexicographically smallest permutation of a string with given subsequences
- Queries to answer the X-th smallest sub-string lexicographically
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest string obtained after concatenating array
- Swap all occurrences of two characters to get lexicographically smallest string
- Find the lexicographically smallest string which satisfies the given condition
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Smallest length string with repeated replacement of two distinct adjacent
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.