Given a string str of length N, the task is to obtain the lexicographically largest string by at most one swap.
Note: The swapping characters might not be adjacent.
Input: str = “string”
Lexicographically largest string obtained by swapping string -> tsring.
Input: str = “zyxw”
The given string is already lexicographically largest.
To solve the above-mentioned problem, the main idea is to use Sorting and compute the largest lexicographical string possible for the given string. After sorting the given string in descending order, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string.
str = “geeks”
Sorted string in descending order = “skgee”.
The first unmatched character is in the first place. This character needs to be swapped with the character at this position in the sorted string which results in the lexicographically largest string. On replacing “g” with the “s”, the string obtained is “seekg” which is lexicographically largest after one swap.
Below is the implementation of the above approach:
- Swap all occurrences of two characters to get lexicographically smallest string
- Lexicographically largest sub-sequence of the given string
- Find the lexicographically largest palindromic Subsequence of a String
- Lexicographically largest string formed from the characters in range L and R
- Lexicographically smallest array formed by at most one swap for every pair of adjacent indices
- Lexicographically smallest and largest substring of size k
- Lexicographically largest subsequence such that every character occurs at least k times
- Largest number with one swap allowed
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Maximize distance between smallest and largest Array elements by a single swap
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically next string
- Lexicographically first palindromic string
- Lexicographically middle string
- Lexicographically n-th permutation of a string
- Lexicographically minimum string rotation | Set 1
- Lexicographically smallest string of length N and sum K
- Find n-th lexicographically permutation of a string | Set 2
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.