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:
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.
- Generate permutations with only adjacent swaps allowed
- Find lexicographically smallest string in at most one swaps
- Make the string lexicographically smallest and non palindromic by swapping of adjacent pair of characters
- Lexicographically smallest and largest anagrams of a string containing another string as its substring
- Minimum number of adjacent swaps to convert a string into its given anagram
- Lexicographically smallest string whose hamming distance from given string is exactly K
- 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 permutation of a string that contains all substrings of another string
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
- Minimum string such that every adjacent character of given string is still adjacent
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Lexicographically smallest string of length N and sum K
- Make the string lexicographically smallest and non palindromic by replacing exactly one character
- Lexicographically smallest string obtained after concatenating array
- Lexicographically smallest permutation of a string with given subsequences
- Lexicographically smallest string formed by removing at most one character
- Find the lexicographically smallest string which satisfies the given condition
- Queries to answer the X-th smallest sub-string lexicographically
- Swap all occurrences of two characters to get lexicographically smallest string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.