KatInterview

267. Palindrome Permutation II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Backtracking

The problem asks for all unique palindromic permutations of a string s. A key property of palindromes is central to the solution: a string can be permuted to form a palindrome if and only if at most one of its characters appears an odd number of times.

Solution

Palindrome Permutation II in Python

from collections import Counter

class Solution:
    def generatePalindromes(self, s: str) -> List[str]:
        # Step 1: Count character frequencies
        counts = Counter(s)
        
        # Step 2: Check for palindrome feasibility and find the middle character
        middle = ""
        half = ""
        for char, count in counts.items():
            if count % 2 != 0:
                if middle:
                    return [] # More than one character with an odd count
                middle = char
            half += char * (count // 2)
        
        # Step 3: Generate permutations of the first half
        result = []
        half_list = sorted(list(half))
        used = [False] * len(half_list)
        
        def backtrack(current_perm):
            # Base case: a full permutation of the half string is formed
            if len(current_perm) == len(half_list):
                first_half = "".join(current_perm)
                result.append(first_half + middle + first_half[::-1])
                return

            # Recursive step: explore choices
            for i in range(len(half_list)):
                if used[i]:
                    continue
                # Skip duplicates
                if i > 0 and half_list[i] == half_list[i-1] and not used[i-1]:
                    continue
                
                used[i] = True
                current_perm.append(half_list[i])
                backtrack(current_perm)
                current_perm.pop() # Backtrack
                used[i] = False

        backtrack([])
        return result

Palindrome Permutation II in Java

class Solution {
    private List<String> result = new ArrayList<>();
    private String middle = "";
    private char[] halfChars;

    public List<String> generatePalindromes(String s) {
        // Step 1: Count character frequencies
        int[] counts = new int[128];
        for (char c : s.toCharArray()) {
            counts[c]++;
        }

        // Step 2: Check for palindrome feasibility and find the middle character
        int oddCount = 0;
        StringBuilder halfSb = new StringBuilder();
        for (int i = 0; i < 128; i++) {
            if (counts[i] % 2 != 0) {
                oddCount++;
                middle = String.valueOf((char) i);
            }
            for (int j = 0; j < counts[i] / 2; j++) {
                halfSb.append((char) i);
            }
        }

        if (oddCount > 1) {
            return new ArrayList<>(); // More than one character with an odd count
        }
        
        halfChars = halfSb.toString().toCharArray();
        boolean[] used = new boolean[halfChars.length];
        
        // Step 3: Generate permutations of the first half
        backtrack(new StringBuilder(), used);
        
        return result;
    }

    private void backtrack(StringBuilder currentPerm, boolean[] used) {
        // Base case: a full permutation of the half string is formed
        if (currentPerm.length() == halfChars.length) {
            String firstHalf = currentPerm.toString();
            String secondHalf = new StringBuilder(firstHalf).reverse().toString();
            result.add(firstHalf + middle + secondHalf);
            return;
        }

        // Recursive step: explore choices
        for (int i = 0; i < halfChars.length; i++) {
            if (used[i]) {
                continue;
            }
            // Skip duplicates
            if (i > 0 && halfChars[i] == halfChars[i-1] && !used[i-1]) {
                continue;
            }

            used[i] = true;
            currentPerm.append(halfChars[i]);
            backtrack(currentPerm, used);
            currentPerm.deleteCharAt(currentPerm.length() - 1); // Backtrack
            used[i] = false;
        }
    }
}

Palindrome Permutation II in C++

class Solution {
public:
    vector<string> generatePalindromes(string s) {
        // Step 1: Count character frequencies
        unordered_map<char, int> counts;
        for (char c : s) {
            counts[c]++;
        }

        // Step 2: Check for palindrome feasibility and find the middle character
        string middle = "";
        string half = "";
        int odd_count = 0;
        for (auto const& [key, val] : counts) {
            if (val % 2 != 0) {
                odd_count++;
                middle += key;
            }
            half += string(val / 2, key);
        }

        if (odd_count > 1) {
            return {}; // More than one character with an odd count
        }

        // Step 3: Generate permutations of the first half
        vector<string> result;
        sort(half.begin(), half.end()); // Sort to handle duplicates
        vector<bool> used(half.size(), false);
        string current_perm = "";
        backtrack(half, used, current_perm, result, middle);
        return result;
    }

private:
    void backtrack(string& half, vector<bool>& used, string& current_perm, vector<string>& result, string& middle) {
        // Base case: a full permutation of the half string is formed
        if (current_perm.length() == half.length()) {
            string reversed_half = current_perm;
            reverse(reversed_half.begin(), reversed_half.end());
            result.push_back(current_perm + middle + reversed_half);
            return;
        }

        // Recursive step: explore choices
        for (int i = 0; i < half.length(); ++i) {
            if (used[i]) {
                continue;
            }
            // Skip duplicates: if current char is same as previous, 
            // and previous was not used, it means we are creating a duplicate permutation.
            if (i > 0 && half[i] == half[i-1] && !used[i-1]) {
                continue;
            }

            used[i] = true;
            current_perm.push_back(half[i]);
            backtrack(half, used, current_perm, result, middle);
            current_perm.pop_back(); // Backtrack
            used[i] = false;
        }
    }
};

Palindrome Permutation II in TypeScript

function generatePalindromes(s: string): string[] {
    // Step 1: Count character frequencies
    const counts = new Map<string, number>();
    for (const char of s) {
        counts.set(char, (counts.get(char) || 0) + 1);
    }

    // Step 2: Check for palindrome feasibility and find the middle character
    let middle = "";
    let half = "";
    let oddCount = 0;
    for (const [char, count] of counts.entries()) {
        if (count % 2 !== 0) {
            oddCount++;
            middle = char;
        }
        half += char.repeat(Math.floor(count / 2));
    }

    if (oddCount > 1) {
        return []; // More than one character with an odd count
    }

    // Step 3: Generate permutations of the first half
    const result: string[] = [];
    const halfChars = half.split('').sort();
    const used = new Array(halfChars.length).fill(false);

    function backtrack(currentPerm: string[]) {
        // Base case: a full permutation of the half string is formed
        if (currentPerm.length === halfChars.length) {
            const firstHalf = currentPerm.join('');
            const secondHalf = currentPerm.slice().reverse().join('');
            result.push(firstHalf + middle + secondHalf);
            return;
        }

        // Recursive step: explore choices
        for (let i = 0; i < halfChars.length; i++) {
            if (used[i]) {
                continue;
            }
            // Skip duplicates
            if (i > 0 && halfChars[i] === halfChars[i-1] && !used[i-1]) {
                continue;
            }

            used[i] = true;
            currentPerm.push(halfChars[i]);
            backtrack(currentPerm);
            currentPerm.pop(); // Backtrack
            used[i] = false;
        }
    }

    backtrack([]);
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.