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
๐Ÿฆ‹ Building a Palindrome Like a Symmetric ButterflyInput: "aabbcc"Step 1: Count Charactersa:2b:2c:2Step 2: Build Left Wingabc"abc"Step 3: Center Bodyโˆ…No odd countsStep 4: Mirror Right Wingabccba"cba"๐ŸŽฏ Beautiful Symmetric Result:"abccba"
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.
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
28.6K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen