Practice LeetCode 131 · Palindrome Partitioning · GFG · Palindrome Partitioning
RecursionBacktrackingPartitionPalindrome

Palindrome Partitioning

Split a string so every piece reads the same forwards and back. At each position, try every prefix, keep only the palindromic ones, and recurse on the rest.

Cut at every valid prefix

From index start, try each prefix s[start..end]. If it's a palindrome, commit that cut, add the piece to the path, and recurse from end+1. Undo the cut to try a longer prefix.

The palindrome prune

  • Non-palindromic prefix → skip that branch
  • Palindromic → recurse on the remainder
  • start == n → the whole string is partitioned
  • Only palindromic-prefix branches survive

Partition into palindromes

Committed piece Testing prefix Valid cut Not a palindrome
slowfast
Step 0
Prefixes tested
0
Partitions found
0
Rejected cuts
0
Depth
0

C++

bool isPal(string& s, int l, int r) {
    while (l < r) if (s[l++] != s[r--]) return false;
    return true;
}

void dfs(int start, string& s,
         vector<string>& path, vector<vector<string>>& out) {
    if (start == s.size()) {         // whole string consumed
        out.push_back(path);
        return;
    }
    for (int end = start; end < s.size(); end++) {
        if (!isPal(s, start, end)) continue;  // prune: not a palindrome
        path.push_back(s.substr(start, end - start + 1));  // CHOOSE
        dfs(end + 1, s, path, out);   // EXPLORE remainder
        path.pop_back();                // UNCHOOSE
    }
}

vector<vector<string>> partition(string s) {
    vector<vector<string>> out; vector<string> path;
    dfs(0, s, path, out);
    return out;
}
Time
O(2ⁿ · n)

Up to 2ⁿ⁻¹ ways to cut, each palindrome check O(n).

Space
O(n)

Recursion depth and the current partition path.

Prune
isPal

Only palindromic prefixes spawn a subtree, killing most branches.

  • The cut points are the choices. Between every pair of characters you either cut or don't, that's the 2ⁿ⁻¹ decision space, filtered by the palindrome test.
  • Precompute an isPal[i][j] DP table to make each check O(1) instead of O(n).
  • Single characters are always palindromes, so a valid partition always exists (worst case, all singletons).
  • Min cuts (LC 132) is the optimization variant, solved with DP rather than enumerating every partition.
  • Same "try every prefix" shape appears in word break and IP-address restoration.