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 whose hamming distance from given string is exactly K
- Lexicographically smallest permutation of a string with given subsequences
- Queries to answer the X-th smallest sub-string lexicographically
- K-th lexicographically smallest unique substring of a given string
- Find the lexicographically smallest string which satisfies the given condition
- Lexicographically smallest string obtained after concatenating array
- Lexicographically smallest string formed by removing at most one character
- 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
- Lexicographically smallest rotated sequence | Set 2
- Construct lexicographically smallest palindrome
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
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.