Smallest Palindromic Rearrangement I - Problem
Given a palindromic string s, you need to find the lexicographically smallest palindromic permutation of that string.
A palindromic permutation is any rearrangement of the characters in s that reads the same forwards and backwards. Since s is already a palindrome, we know that at least one palindromic permutation exists.
Goal: Return the lexicographically smallest palindromic permutation of s.
Example: If s = "aabaa", possible palindromic permutations include "aabaa", "abaaa", but the lexicographically smallest is "aaaaa" - wait, that's not a palindrome! The correct answer is "aabaa" when rearranged optimally.
Input & Output
example_1.py โ Basic Case
$
Input:
"aabaa"
โบ
Output:
"aabaa"
๐ก Note:
The input is already a palindrome, and it's already the lexicographically smallest permutation of its characters that forms a palindrome.
example_2.py โ Rearrangement Needed
$
Input:
"aabbcc"
โบ
Output:
"abccba"
๐ก Note:
Count: a:2, b:2, c:2. Left half gets one of each character in alphabetical order: 'abc'. No middle character needed (all counts are even). Right half is reverse of left: 'cba'. Result: 'abccba'.
example_3.py โ With Middle Character
$
Input:
"aabbbcc"
โบ
Output:
"abcbbca"
๐ก Note:
Count: a:2, b:3, c:2. Left half: 'abc' (1 of each, taking floor of count/2). Middle: 'b' (the only character with odd count). Right half: 'cba'. Result: 'abcbbca'.
Constraints
- 1 โค s.length โค 1000
- s consists of lowercase English letters only
- s is guaranteed to be a palindrome
- There will always be at least one palindromic permutation
Visualization
Tap to expand
Understanding the Visualization
1
Count the Paint Colors
Count how many times each character appears in the string
2
Design the Left Wing
Use half of each character count to build the left side in alphabetical order
3
Place the Body
If any character has an odd count, place one in the center
4
Mirror the Right Wing
Reverse the left side to create the right side, completing the palindrome
Key Takeaway
๐ฏ Key Insight: A palindrome is perfectly symmetric - optimize one half alphabetically, then mirror it. This avoids generating unnecessary permutations and directly constructs the lexicographically smallest result in O(n) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code