Smallest Palindromic Rearrangement I - Problem

You are given a palindromic string s. Return the lexicographically smallest palindromic permutation of s.

A palindromic string reads the same forward and backward. A lexicographically smaller string is one that would appear earlier in dictionary order.

Since the input is already a palindrome, we need to find the smallest possible rearrangement that maintains the palindromic property.

Input & Output

Example 1 — Basic Rearrangement
$ Input: s = "aabcc"
Output: "acbca"
💡 Note: The input "aabcc" can be rearranged to form "acbca" which is a palindrome. This is the lexicographically smallest palindromic permutation possible.
Example 2 — Already Optimal
$ Input: s = "aba"
Output: "aba"
💡 Note: The string "aba" is already a palindrome and in its lexicographically smallest form, so we return it as is.
Example 3 — Single Character
$ Input: s = "a"
Output: "a"
💡 Note: A single character is always a palindrome and is already in its smallest form.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters
  • s is guaranteed to be a palindrome

Visualization

Tap to expand
Smallest Palindromic Rearrangement INPUT Palindromic String s: a a b c c 0 1 2 3 4 Character Count: a: 2 b: 1 c: 2 Length: 5 (odd) Middle char needed: Yes s = "aabcc" ALGORITHM STEPS 1 Count Characters Track frequency of each char 2 Sort Characters Arrange in lex order: a,b,c 3 Build Half String Take half of each pair: "ac" 4 Create Palindrome half + middle + reverse(half) Construction: a c + b + c a half mid rev FINAL RESULT Smallest Palindrome: a c b c a Mirror symmetry Verification: Palindrome: OK (reads same) Lex smallest: OK (a first) Output: "acbca" Key Insight: For the lexicographically smallest palindrome, sort characters and place smallest ones at the edges. Use half of each pair for the first half, put any odd-count character in the middle, then mirror the first half to create the palindrome. TutorialsPoint - Smallest Palindromic Rearrangement I | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
456 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