Given a string S. Print the lexicographically smallest string possible. You can make minimal changes to the characters in the string and you can permute the string.
Input : S = "aabc" Output : "abba" Input : S = "äabcd" Output : "abcba"
Explanation 1:Change the last index “c” to “b”, it becomes “aabb”. Then rearrange the string, it becomes “abba”. This is the lexicographically smallest string.
Explanation 2: change “d” to “b” => “aabcb” => “abcba”.
cnt[a] be the no.of occurrences of the character a. Consider odd values of cnt[a], then a palindrome can not contain more than one character a with cnt[a]. Denote characters with odd count cnt as follows a1, a2….ak(in alphabetical order). Replace any of the symbols ak with a1 and ak-1 with a2 and so on upto middle of sequence above. Now, there are no more than one odd symbol. Place it in the middle of answer. First half of answer will consist of occurrences of symbol a. Second half will contains same symbols in reverse order.
take string S = "aabcd" cnt[a] = 2, cnt[b] = 1, cnt = 1, cnt[d] = 1. Odd characters => b, c, d replace ak('d') with a1('b') we get => b, c, b. cnt[b] = 2, cnt = 1.Place odd character in middle and 'a' and 'b' in first half and also in second half, we get "abcba".
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes