WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Dynamic Programming · Intermediate · question 34 of 100

Implement the solution to the Palindrome Partitioning problem using dynamic programming.?

📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

The Palindrome Partitioning problem can be stated as follows:

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

For example, given the string s = "aab", the possible palindrome partitionings are:

- ["aa", "b"]
- ["a", "a", "b"]

To solve this problem, we can use dynamic programming. We can use a 2D boolean array to store whether a substring from i to j is a palindrome. Then we can use backtracking to generate all possible palindrome partitionings.

Here’s the Java code:

public List<List<String>> partition(String s) {
    int n = s.length();
    boolean[][] isPalindrome = new boolean[n][n];

    // fill isPalindrome table
    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 || isPalindrome[i + 1][j - 1])) {
                isPalindrome[i][j] = true;
            }
        }
    }

    List<List<String>> result = new ArrayList<>();
    dfs(result, new ArrayList<>(), s, isPalindrome, 0);
    return result;
}

private void dfs(List<List<String>> result, List<String> currentList, String s, boolean[][] isPalindrome, int start) {
    if (start == s.length()) {
        result.add(new ArrayList<>(currentList));
        return;
    }

    for (int end = start; end < s.length(); end++) {
        if (isPalindrome[start][end]) {
            currentList.add(s.substring(start, end + 1));
            dfs(result, currentList, s, isPalindrome, end + 1);
            currentList.remove(currentList.size() - 1);
        }
    }
}

The time complexity of this solution is O(n2) to fill the isPalindrome table, and the space complexity is also O(n2) to store the table. The backtracking part has a time complexity of O(n * 2n), since in the worst-case scenario, every substring is a palindrome and every partition is a single character, resulting in 2n possible partitions. However, in practice, the number of possible partitions is much smaller than 2n.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Dynamic Programming interview — then scores it.
📞 Practice Dynamic Programming — free 15 min
📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

All 100 Dynamic Programming questions · All topics