↓Skip to main content
  1. LeetCode/

LeetCode 131: Palindrome Partitioning

·2 mins· ·
LeetCode Medium String Dynamic-Programming Backtracking
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-30

  • Submissions: Wrong Answer ×3 → Accepted → Wrong Answer → Accepted ×2 → Wrong Answer ×2 → Accepted → Wrong Answer → Accepted

Approach
#

Partition backtracking (Backtracking Variation 5): dfs(start, path) tries s[start:end] as the next piece with end from start + 1 to len(s) (including the whole remainder), recursing only on palindromes. Record when start == len(s). Precomputing isPal[i][j] with DP avoids repeated checks.

My Attempts
#

This took 12 submissions with one core bug:

  • Cut lengths were range(1, len(s)), so the whole remainder was never a piece and the last piece could never be cut: "b" returned [] and "bab" lacked ["bab"]. Attempt 1 also continued from s[i + 1:] (skipping a character) and never called dfs.
  • Rewrites in 2022-10 and 2022-11 failed at the same spot; range(1, len(s) + 1) finally passed.

Solution
#

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res, path = [], []
        def dfs(start):
            if start == len(s):
                res.append(path[:])
                return
            for end in range(start + 1, len(s) + 1):
                piece = s[start:end]
                if piece == piece[::-1]:
                    path.append(piece)
                    dfs(end)
                    path.pop()
        dfs(0)
        return res

Complexity
#

Time O(n · 2^n), space O(n) excluding output.

Mistakes to Avoid
#

  • The cut lengths must include the whole remainder: range(1, len(s) + 1).
  • Continue from s[i:] after cutting, not s[i + 1:].

Interview Explanation
#

I backtrack over cuts: each level takes a prefix of the remainder of every length from 1 to all of it, recursing on palindromes and recording when the string is used up; palindromic ranges can be precomputed with DP.

Related

LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list
LeetCode 5: Longest Palindromic Substring
·2 mins
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 note: expand around centers, using each position as an odd and an even center; with interval DP, iterate i from large to small
LeetCode 208: Implement Trie (Prefix Tree)
·2 mins
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 note: each node is a children dict plus an is_end flag; insert, search and startsWith all walk down character by character
LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k
LeetCode 981: Time Based Key-Value Store
·2 mins
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 note: store a (timestamp, value) list per key, with timestamps increasing; get binary searches the last timestamp <= the query