๐Ÿ—“๏ธ Day 30: Palindrome Partitioning with Backtracking

๐Ÿง  Concept Deep Dive

Palindrome Partitioning is a classic use-case for backtracking. The idea is to split a string into all possible lists of palindromic substrings.

Key characteristics:

  • Use recursion to explore every partition
  • Backtrack when a substring is not a palindrome
  • Track path and add to result when you reach the end

๐ŸŽฏ Visual Intuition

Given: s = "aab"

Recursive Tree:
Start -> "a" + recurse("ab")
             -> "a" + recurse("b")
                       -> "b" + recurse("") โœ…
      -> "aa" + recurse("b")
                  -> "b" + recurse("") โœ…

Result: [["a","a","b"], ["aa","b"]]

We build up paths of palindromes and backtrack when needed.


๐Ÿ› ๏ธ Key Patterns

โ™ป๏ธ Backtracking with Palindrome Check

function partition(s: string): string[][] {
  const res: string[][] = [];

  function backtrack(start: number, path: string[]) {
    if (start === s.length) {
      res.push([...path]);
      return;
    }
    for (let end = start + 1; end <= s.length; end++) {
      const substr = s.slice(start, end);
      if (isPalindrome(substr)) {
        path.push(substr);
        backtrack(end, path);
        path.pop();
      }
    }
  }

  function isPalindrome(str: string): boolean {
    let l = 0, r = str.length - 1;
    while (l < r) {
      if (str[l] !== str[r]) return false;
      l++;
      r--;
    }
    return true;
  }

  backtrack(0, []);
  return res;
}

๐Ÿ“˜ Example

Input: s = "aab"

Output: [["a","a","b"], ["aa","b"]]

Explanation: All possible palindrome partitions.


๐Ÿงช Homework

  1. Write partition(s: string): string[][] using backtracking.
  2. Bonus: Count how many recursive calls happen.
function partition(s: string): string[][] {
  // your code
}

๐Ÿง  Big-O Cheat Sheet

  • Time: O(2^n) โ€” every char may or may not be a cut
  • Space: O(n) recursion stack

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 31: Dynamic Programming on Palindromic Substrings

This page was last edited on 2025-08-01 09:37

Powered by Wiki|Docs

This page was last edited on 2025-08-01 09:37

Tri Nguyen
No Copyright

Powered by Wiki|Docs