#3518

Smallest Palindromic Rearrangement II

Hard
Hash TableMathStringCombinatoricsCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n!)
Space
O(n)
O(n)
💡

Intuition

Time O(n!)Space O(n)

Count character frequencies, build half the palindrome, and generate permutations efficiently. This reduces complexity by leveraging symmetry in palindromes.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count character frequencies and determine half counts for the palindrome.
  2. 2Step 2: Generate the half string and create permutations of it.
  3. 3Step 3: Construct full palindromes and return the k-th lexicographically smallest.
solution.py9 lines
1from collections import Counter
2from itertools import permutations
3
4def kth_palindrome(s, k):
5    count = Counter(s)
6    half = ''.join(char * (count[char] // 2) for char in sorted(count))
7    unique_half = sorted(set(permutations(half)))
8    palindromes = [''.join(h) + ''.join(h)[::-1] for h in unique_half]
9    return palindromes[k-1] if k <= len(palindromes) else ''

Complexity note: Generating permutations of half the string is factorial, but we avoid duplicates using a set.

  • 1Only half of the characters are needed to form a palindrome.
  • 2Distinct arrangements can be generated using character counts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.