KatInterview

131. Palindrome Partitioning

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

The problem asks us to find all possible ways to partition a given string s such that every substring in the partition is a palindrome. For example, if s = "aab", the partitions ["a", "a", "b"] and ["aa", "b"] are valid because all their constituent substrings are palindromes.

Solution

Palindrome Partitioning in Python

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        n = len(s)
        result = []
        path = []
        
        # dp[i][j] will be true if the string from index i to j is a palindrome.
        dp = [[False] * n for _ in range(n)]
        
        # Pre-compute palindrome information using dynamic programming.
        for i in range(n - 1, -1, -1):
            for j in range(i, n):
                # A string is a palindrome if its first and last characters are the same
                # and the inner part is also a palindrome. Length 1 and 2 are base cases.
                if s[i] == s[j] and (j - i < 2 or dp[i+1][j-1]):
                    dp[i][j] = True

        def backtrack(start):
            # Base case: if we've reached the end of the string,
            # we have found a valid partition.
            if start == n:
                result.append(list(path)) # Add a copy of the current path
                return

            # Explore all possible partitions starting from the 'start' index.
            for end in range(start, n):
                # If the substring s[start:end+1] is a palindrome (O(1) lookup).
                if dp[start][end]:
                    # Add the palindrome substring to the current path.
                    path.append(s[start:end + 1])
                    # Recurse for the rest of the string.
                    backtrack(end + 1)
                    # Backtrack: remove the substring to explore other possibilities.
                    path.pop()

        backtrack(0)
        return result

Palindrome Partitioning in Java

class Solution {
    public List<List<String>> partition(String s) {
        int n = s.length();
        List<List<String>> result = new ArrayList<>();
        List<String> currentPath = new ArrayList<>();
        boolean[][] dp = new boolean[n][n];

        // Pre-compute whether s[i..j] is a palindrome using dynamic programming.
        // The logic is that s[i..j] is a palindrome if s.charAt(i) == s.charAt(j) 
        // and the inner part s[i+1..j-1] is also a palindrome.
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i; j < n; j++) {
                if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1])) {
                    dp[i][j] = true;
                }
            }
        }

        backtrack(s, 0, currentPath, result, dp);
        return result;
    }

    private void backtrack(String s, int start, List<String> currentPath, List<List<String>> result, boolean[][] dp) {
        // Base case: If we have reached the end of the string, a valid partition is found.
        if (start == s.length()) {
            // Add a copy of the current path to the result list.
            result.add(new ArrayList<>(currentPath));
            return;
        }

        // Explore all possible substrings starting from the 'start' index.
        for (int end = start; end < s.length(); end++) {
            // If the substring s[start..end] is a palindrome (checked in O(1) using the DP table).
            if (dp[start][end]) {
                // Add the palindrome substring to the current path.
                currentPath.add(s.substring(start, end + 1));
                
                // Recurse on the remaining part of the string.
                backtrack(s, end + 1, currentPath, result, dp);
                
                // Backtrack: remove the last added substring to explore other possibilities.
                currentPath.remove(currentPath.size() - 1);
            }
        }
    }
}

Palindrome Partitioning in C++

class Solution {
public:
    vector<vector<string>> partition(string s) {
        int n = s.length();
        vector<vector<string>> result;
        vector<string> currentPath;
        vector<vector<bool>> dp(n, vector<bool>(n, false));

        // Pre-compute whether s[i..j] is a palindrome using dynamic programming.
        // The logic is that s[i..j] is a palindrome if s[i] == s[j] and the inner part s[i+1..j-1] is also a palindrome.
        for (int i = n - 1; i >= 0; --i) {
            for (int j = i; j < n; ++j) {
                if (s[i] == s[j] && (j - i < 2 || dp[i + 1][j - 1])) {
                    dp[i][j] = true;
                }
            }
        }

        backtrack(s, 0, currentPath, result, dp);
        return result;
    }

private:
    void backtrack(const string& s, int start, vector<string>& currentPath, vector<vector<string>>& result, const vector<vector<bool>>& dp) {
        // Base case: If we have reached the end of the string, a valid partition is found.
        if (start == s.length()) {
            result.push_back(currentPath);
            return;
        }

        // Explore all possible substrings starting from the 'start' index.
        for (int end = start; end < s.length(); ++end) {
            // If the substring s[start..end] is a palindrome (checked in O(1) using the DP table).
            if (dp[start][end]) {
                // Add the palindrome substring to the current path.
                currentPath.push_back(s.substr(start, end - start + 1));
                
                // Recurse on the remaining part of the string.
                backtrack(s, end + 1, currentPath, result, dp);
                
                // Backtrack: remove the last added substring to explore other possibilities.
                currentPath.pop_back();
            }
        }
    }
};

Palindrome Partitioning in TypeScript

function partition(s: string): string[][] {
    const n = s.length;
    const result: string[][] = [];
    const currentPath: string[] = [];
    const dp: boolean[][] = Array(n).fill(0).map(() => Array(n).fill(false));

    // Pre-compute whether s[i..j] is a palindrome using dynamic programming.
    // The logic is that s[i..j] is a palindrome if s[i] === s[j] and 
    // the inner part s[i+1..j-1] is also a palindrome.
    for (let i = n - 1; i >= 0; i--) {
        for (let j = i; j < n; j++) {
            if (s[i] === s[j] && (j - i < 2 || dp[i + 1][j - 1])) {
                dp[i][j] = true;
            }
        }
    }

    function backtrack(start: number) {
        // Base case: If we have reached the end of the string, a valid partition is found.
        if (start === n) {
            result.push([...currentPath]); // Add a copy of the current path
            return;
        }

        // Explore all possible substrings starting from the 'start' index.
        for (let end = start; end < n; end++) {
            // If the substring s[start..end] is a palindrome (checked in O(1) using the DP table).
            if (dp[start][end]) {
                // Add the palindrome substring to the current path.
                currentPath.push(s.substring(start, end + 1));
                
                // Recurse on the remaining part of the string.
                backtrack(end + 1);
                
                // Backtrack: remove the last added substring to explore other possibilities.
                currentPath.pop();
            }
        }
    }

    backtrack(0);
    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.