Smallest Palindromic Rearrangement II - Problem

Given a palindromic string s and an integer k, your task is to find the k-th lexicographically smallest palindromic permutation of the characters in s.

Key points:

  • The input string s is already a palindrome
  • You need to rearrange its characters to form different palindromes
  • Return the k-th smallest palindrome in lexicographical order
  • If there are fewer than k distinct palindromic permutations, return an empty string
  • Different arrangements that create the same palindromic string count as one permutation

Example: For s = "aab" and k = 2, the palindromic permutations are ["aba", "baa"], so return "baa".

Input & Output

example_1.py — Basic Case
$ Input: s = "aab", k = 2
Output: "baa"
💡 Note: The palindromic permutations of "aab" are ["aba", "baa"] in lexicographical order. The 2nd one is "baa".
example_2.py — Single Character
$ Input: s = "aaa", k = 1
Output: "aaa"
💡 Note: Only one palindromic permutation exists: "aaa". Since k=1, return "aaa".
example_3.py — Impossible Case
$ Input: s = "abc", k = 1
Output: ""
💡 Note: "abc" cannot form any palindromic permutation because all characters appear with odd frequency (more than one odd frequency character).

Constraints

  • 1 ≤ s.length ≤ 16
  • s consists of only lowercase English letters
  • s is a palindromic string
  • 1 ≤ k ≤ 109
  • The input string s is guaranteed to be a palindrome

Visualization

Tap to expand
Smallest Palindromic Rearrangement II INPUT Palindromic String s 'a' 'a' 'b' idx: 0 idx: 1 idx: 2 Target Position k = 2 Character Count 'a': 2 'b': 1 s = "aab" k = 2 ALGORITHM STEPS 1 Count Characters Half counts for palindrome 2 Generate Half Perms Sort lexicographically 3 Find k-th Half Use factorial ranking 4 Build Full Palindrome Mirror + middle char All Palindrome Permutations: Rank Palindrome 1 "aba" 2 "baa" -- k=2 Half: "a" --> "ba" (mirror) Middle: none (odd handled) FINAL RESULT 2nd Smallest Palindrome 'b' 'a' 'a' Palindrome Structure: "b" + "aa" + "" + "b" (half + middle + reverse) Output: "baa" OK - Valid Key Insight: For palindromes, only the first half matters! Count character frequencies, divide by 2 for half-string. Use factorial-based ranking to find k-th permutation efficiently without generating all permutations. Total permutations = (n/2)! / (freq[c]/2)! for each char. If k exceeds this count, return empty string. TutorialsPoint - Smallest Palindromic Rearrangement II | Optimal Solution
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
28.4K Views
Medium Frequency
~35 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