Smallest Palindromic Rearrangement I (LeetCode 3517): Solution and Explanation
Given a palindrome, rearrange its letters into the lexicographically smallest palindrome possible.
Intuition
A palindrome is fixed once you know its left half and, for odd length, its middle letter. The right half is just the left half reversed.
Because s is already a palindrome, every letter appears an even number of times except at most one, and that odd one has to be the middle.
Comparison starts at the first character, so the left half should hold the smallest letters first: put the halves in sorted order.
Approach: Counting sort of the left half, then mirror
- Count each letter of
s. - For each letter from a to z, append
cnt // 2copies tohalf; if its count is odd, it becomesmid. - Return
half + mid + reverse(half).
Step-by-step example
s = "babab"
- Counts: a = 2, b = 3.
- 'a' gives one pair: slots 0 and 4 get 'a'.
- 'b' has an odd count, so one 'b' goes to the middle slot 2, and its remaining pair fills slots 1 and 3.
- The result is "abbba".
Code: Python, Java, C++
1class Solution:
2 def smallestPalindrome(self, s: str) -> str:
3 cnt = [0] * 26
4 for ch in s:
5 cnt[ord(ch) - ord('a')] += 1
6 half, mid = [], ''
7 for i in range(26):
8 ch = chr(i + 97)
9 if cnt[i] % 2 == 1:
10 mid = ch
11 half.append(ch * (cnt[i] // 2))
12 left = ''.join(half)
13 return left + mid + left[::-1]1class Solution {
2 public String smallestPalindrome(String s) {
3 int[] cnt = new int[26];
4 for (char ch : s.toCharArray()) {
5 cnt[ch - 'a']++;
6 }
7 StringBuilder half = new StringBuilder();
8 String mid = "";
9 for (int i = 0; i < 26; i++) {
10 char ch = (char) ('a' + i);
11 if (cnt[i] % 2 == 1) {
12 mid = String.valueOf(ch);
13 }
14 for (int k = 0; k < cnt[i] / 2; k++) {
15 half.append(ch);
16 }
17 }
18 String left = half.toString();
19 return left + mid + half.reverse().toString();
20 }
21}1class Solution {
2public:
3 string smallestPalindrome(string s) {
4 int cnt[26] = {0};
5 for (char ch : s) {
6 cnt[ch - 'a']++;
7 }
8 string half, mid;
9 for (int i = 0; i < 26; i++) {
10 char ch = 'a' + i;
11 if (cnt[i] % 2 == 1) {
12 mid = string(1, ch);
13 }
14 half += string(cnt[i] / 2, ch);
15 }
16 string right(half.rbegin(), half.rend());
17 return half + mid + right;
18 }
19};Time and space complexity
O(n)
Counting is one pass and building the output writes each character once. No comparison sort is needed because the alphabet has 26 letters.
O(n)
The output string has n characters; the counts take 26 slots.
Other approaches
Sort the first half directly (time O(n log n), space O(n))
Take s[:n // 2], sort it, and return half + s[n // 2] (if odd) + half[::-1]. Since s is a palindrome, its first half already holds exactly one of each pair. Simple, but the sort costs O(n log n).
Sort the whole string and pick every other letter (time O(n log n), space O(n))
Sorting all of s and taking pairs also works, but it is more work than counting for no gain.
Common mistakes
- Sorting the whole string instead of building a palindrome: "aabbb" sorted is not a palindrome.
- Forgetting the middle letter for odd lengths, which drops one character from the answer.
- Mirroring a mutable builder in place and then reading it again; in Java, save the left half before calling
reverse().
Frequently asked questions
Why can there be at most one odd count?
Every position in a palindrome is paired with its mirror, except the middle one in an odd-length string. So only one letter can have an unpaired copy.
Why does sorting the left half give the smallest palindrome?
The left half is compared before anything else, and it can hold any arrangement of the pairs. Sorted order is the smallest arrangement, and the rest of the string is then forced.
Can the answer equal the input?
Yes, for example "aba" or "aaaa" are already the smallest arrangement.