#3517
Smallest Palindromic Rearrangement I
MediumStringSortingCounting SortHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Count characters, build half the palindrome, then mirror it. This is efficient and leverages the properties of palindromes.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in the string.
- 2Step 2: Construct half of the palindrome using the sorted characters.
- 3Step 3: Mirror the half to form the full palindrome.
solution.py6 lines
1from collections import Counter
2
3def smallest_palindrome(s):
4 count = Counter(s)
5 half = ''.join(sorted(c * (freq // 2) for c, freq in count.items()))
6 return half + half[::-1] if len(s) % 2 == 0 else half + min(count) + half[::-1]ℹ
Complexity note: Counting characters is O(n), sorting keys is O(k log k) where k is the number of unique characters.
- 1Palindromes are symmetrical.
- 2Character frequency determines palindrome structure.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.