Given a string str of length N. The task is to find out the lexicographically smallest string when at most only one swap is allowed. That is, two indices 1 <= i, j <= n can be chosen and swapped. This operation can be performed at most one time.
Input: str = “string”
Choose i=1, j=6, string becomes – gtrins. This is lexicographically smallest strings that can be formed.
Input: str = “zyxw”
Approach: The idea is to use sorting and compute the smallest lexicographical string possible for the given string. After computing the sorted string, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string.
For example, let str = “geeks” and the sorted = “eegks”. First unmatched character is in the first place. This character has to swapped such that this character matches the character with sorted string. Resulting lexicographical smallest string. On replacing “g” with the last occurring “e”, the string becomes eegks which is lexicographically smallest.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Lexicographically smallest array after at-most K consecutive swaps
- Find the lexicographically smallest string which satisfies the given condition
- 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
- Queries to answer the X-th smallest sub-string lexicographically
- K-th lexicographically smallest unique substring of a given string
- Lexicographically smallest permutation of a string with given subsequences
- Lexicographically smallest string obtained after concatenating array
- Lexicographically smallest string formed by removing at most one character
- Swap all occurrences of two characters to get lexicographically smallest string
- Make the string lexicographically smallest and non palindromic by replacing exactly one character
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
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.