Palindrome Permutation II - Problem

Given a string s, return all the palindromic permutations (without duplicates) of it.

You may return the answer in any order. If s has no palindromic permutation, return an empty list.

A palindromic permutation is a rearrangement of the string's characters that reads the same forwards and backwards.

Input & Output

Example 1 — Basic Case
$ Input: s = "aab"
Output: ["aba"]
💡 Note: Character frequencies: a=2, b=1. Only one odd frequency (b), so palindrome possible. Arranging pairs 'a' around center 'b' gives 'aba'.
Example 2 — Multiple Palindromes
$ Input: s = "aabb"
Output: ["abba", "baab"]
💡 Note: All characters have even frequencies. Can arrange pairs in 2 ways: 'a' pairs outside 'b' pairs gives 'abba', or 'b' pairs outside 'a' pairs gives 'baab'.
Example 3 — Impossible Case
$ Input: s = "abc"
Output: []
💡 Note: All characters have frequency 1 (3 odd frequencies). Since more than 1 character has odd frequency, no palindromic permutation is possible.

Constraints

  • 1 ≤ s.length ≤ 16
  • s contains only lowercase English letters

Visualization

Tap to expand
Palindrome Permutation II INPUT String s = "aab" a a b Character Frequency 'a': 2 'b': 1 Odd count chars: 1 (OK for palindrome) Input String: s = "aab" ALGORITHM STEPS 1 Count Characters Build frequency map 2 Check Validity Max 1 odd count char 3 Build Half String Use half of each char 4 Backtrack Permute Generate + mirror halves Half: "a" | Mid: "b" "a" + "b" + "a" = "aba" Permute half, append mid, mirror for full palindrome FINAL RESULT Palindromic Permutation: a b a Mirrored Palindrome Check: OK "aba" reads same both ways Output Array: ["aba"] Key Insight: A string can form a palindrome only if at most ONE character has an odd frequency. Build half the palindrome using backtracking, then mirror it. The middle char (if odd count) goes in the center. Time: O(n! / 2^n) for generating permutations, Space: O(n). TutorialsPoint - Palindrome Permutation II | Optimal Solution (Backtracking)
Asked in
Facebook 25 Google 20 Amazon 15
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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