Smallest Palindromic Rearrangement I Problem
#3517
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3517.
You are given a palindromic string s.
Return the lexicographically smallest palindromic permutation of s.
Example 1:
Input: s = "z"
Output: "z"
Explanation:
A string of only one character is already the lexicographically smallest palindrome.
Example 2:
Input: s = "babab"
Output: "abbba"
Explanation:
Rearranging "babab" → "abbba" gives the smallest lexicographic palindrome.
Example 3:
Input: s = "daccad"
Output: "acddca"
Explanation:
Rearranging "daccad" → "acddca" gives the smallest lexicographic palindrome.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters.sis guaranteed to be palindromic.
Solution
Approach: Counting
Count each letter. Because s is a palindrome, every count is even except possibly one letter, which sits in the middle.
Build the first half by going through the letters from a to z and appending each letter count / 2 times; this is the smallest possible half. The letter with an odd count, if any, is the middle character. The answer is the first half, then the middle character, then the first half reversed.
Complexity: O(n) time and O(1) extra space (26 counters).
from collections import Counter
from string import ascii_lowercase
class Solution:
def smallestPalindrome(self, s: str) -> str:
cnt = Counter(s)
t = []
ch = ""
for c in ascii_lowercase:
v = cnt[c] // 2
t.append(c * v)
cnt[c] -= v * 2
if cnt[c] == 1:
ch = c
ans = "".join(t)
ans = ans + ch + ans[::-1]
return ans