DDSA Solutions

Find all possible palindromic partitions of a String

Advertisement

Intuition

Find all ways to partition string so every substring is a palindrome. Backtracking + palindrome precompute.

Algorithm

  1. 1Precompute isPalin[i][j] with DP. Backtrack: at each position, try all palindromic substrings starting here.

Common Pitfalls

  • Same as LC 131. Precompute palindrome table in O(n^2). Backtrack with O(n) palindrome check or use the table.
Find all possible palindromic partitions of a String.java
Java
// Approach: Backtracking. At each position, try all prefixes that are palindromes, recurse on remainder.
// Time: O(n * 2^n) Space: O(n)
import java.util.*;

class Solution {
    public ArrayList<ArrayList<String>> palinParts(String s) {
        ArrayList<ArrayList<String>> result = new ArrayList<>();
        backtrack(0, s, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int start, String s, ArrayList<String> current, ArrayList<ArrayList<String>> result) {
        if (start == s.length()) {
            result.add(new ArrayList<>(current));
            return;
        }

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

    private boolean isPalindrome(String s, int left, int right) {
        while (left < right) {
            if (s.charAt(left++) != s.charAt(right--))
                return false;
        }
        return true;
    }
}
Advertisement
Was this solution helpful?