Swap all occurrences of two characters to get lexicographically smallest string

Given a string str of lower case English alphabets. One can choose any two characters in the string and replace all the occurrences of the first character with the second character and replace all the occurrences of the second character with the first character. Find the lexicographically smallest string that can be obtained by doing this operation at most once.

Examples:

Input: str = “ccad”
Output: aacd
Swap all the occurrences of ‘c’ with ‘a’ and all the
occurrences of ‘a’ with ‘c’ to get “aacd” which is the
lexicographically smallest string that we can get.

Input: str = “abba”
Output: abba
The only possible operation will convert the given string
to “baab” which is not lexicographically smallest.

Approach:



Article Tags :
Practice Tags :