Problem 131

Abstract / Summary

Given a string, find all possible ways to split it into substrings so that each part reads the same forwards and backwards.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0131.py

class Solution:
    @cache
    def isPalindrome(self, s):
        if len(s) == 1:
            return True
        halfsize = len(s) // 2
        return s[0:halfsize] == s[-halfsize:][::-1]

    @cache
    def deeper(self, s):
        size = len(s)
        if size == 0:
            return None
        if size == 1:
            return [ [ s ] ]

        result = []
        for i in range(1, size+1):
            current = s[:i]
            other   = s[i:]

            if not self.isPalindrome(current):
                continue

            next = self.deeper(other)
            if not next:
                result.append([ current ])
                continue
            for x in next:
                result.append([ current ] + x)

        return result

    def partition(self, s: str) -> List[List[str]]:
        return self.deeper(s)
35 lines | 877 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (1+ million submissions).

Typical patterns to solve this problem:
  • Backtracking
  • Dynamic Programming
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class that solves the classic string-partition-into-palindromes problem. The public entry point is the partition method, which delegates the work to a recursive helper named deeper. Two auxiliary methods, isPalindrome and deeper, are memoized with @cache to avoid redundant calculations. The algorithm explores every possible prefix that forms a palindrome, then recursively partitions the remaining suffix, building up a list of all valid palindrome partitions.

Core Components

Palindrome Check

@cache
def isPalindrome(self, s):
    if len(s) == 1:
        return True
    halfsize = len(s) // 2
    return s[0:halfsize] == s[-halfsize:][::-1]

The isPalindrome function determines whether a given substring s reads the same forward and backward. For a single-character string it returns True immediately, handling the minimal palindrome case. For longer strings it compares the first half with the reversed second half, which works for both even and odd lengths because integer division discards the middle character when the length is odd. The use of slicing avoids explicit loops and leverages Python’s optimized C-level operations.

Recursive Partition Builder

@cache
def deeper(self, s):
    size = len(s)
    if size == 0:
        return None
    if size == 1:
        return [[s]]

    result = []
    for i in range(1, size + 1):
        current = s[:i]
        other   = s[i:]

        if not self.isPalindrome(current):
            continue

        next = self.deeper(other)
        if not next:
            result.append([current])
            continue
        for x in next:
            result.append([current] + x)

    return result

deeper is the engine that constructs all palindrome partitions for the input string s. It first handles two base conditions: an empty string yields None, signalling that no further partitioning is possible, while a single-character string returns a list containing a single partition consisting of that character.

The method then iterates over every possible split point i, extracting current as the prefix s[:i] and other as the remaining suffix s[i:]. The palindrome check filters out prefixes that are not palindromes, pruning the search space early. When a palindrome prefix is found, the function recursively processes the suffix. If the recursive call returns a falsy value (i.e., None), the algorithm records the palindrome prefix as a complete partition. Otherwise, it concatenates the prefix with each partition returned from the recursive call, building up larger partition lists.

Public Interface

def partition(self, s: str) -> List[List[str]]:
    return self.deeper(s)

The partition method simply forwards the input string to deeper, exposing the full set of palindrome partitions to callers.

Edge Cases Handled

The code explicitly addresses several boundary conditions:

  • Empty Input - When s is an empty string, deeper returns None. This signals that no partition exists, and the caller receives an empty result set.
  • Single-Character Input - Both isPalindrome and deeper treat a string of length one as a palindrome and as a complete partition, respectively. This ensures that the trivial case is covered without unnecessary recursion.
  • Odd-Length Palindromes - The palindrome check computes halfsize using integer division, which discards the central character for odd lengths. The comparison therefore correctly ignores the middle character, allowing strings like "aba" to be recognized as palindromes.
  • Non-Palindromic Prefixes - The loop in deeper skips any prefix that fails the palindrome test, preventing the algorithm from descending into branches that cannot lead to valid partitions.

Performance Optimizations

Two primary techniques improve the efficiency of the solution:

  • Memoization with @cache - Both isPalindrome and deeper are decorated with @cache. This stores the result of each unique call, so repeated evaluations of the same substring avoid recomputation. For isPalindrome, caching eliminates redundant slice comparisons when the same substring appears in multiple recursive paths. For deeper, caching prevents the exponential blow-up that would otherwise arise from recomputing partitions of identical suffixes.

  • Early Pruning of Non-Palindromic Prefixes - By checking self.isPalindrome(current) before invoking the recursive call, the algorithm discards large portions of the search tree early. This reduces the number of recursive invocations and the amount of intermediate data that must be stored.

Additionally, the use of Python’s slice notation (s[:i], s[i:], s[0:halfsize], s[-halfsize:][::-1]) leverages highly optimized internal routines, which are faster than manual character-by-character loops.

Execution Flow

When partition receives a string, it triggers deeper. The recursive process can be visualized as a depth-first traversal of a tree where each node represents a palindrome prefix and each edge leads to the remainder of the string. At each node, the algorithm:

  1. Checks if the current prefix is a palindrome.
  2. If it is, recursively obtains all partitions of the suffix.
  3. Combines the prefix with each suffix partition, or records the prefix alone if the suffix is empty.

The memoization ensures that each distinct suffix is processed only once, and the results are reused wherever that suffix reappears in the recursion tree.

Concluding Remarks

The implementation delivers a complete enumeration of palindrome partitions through a clean recursive design, reinforced by memoization and strategic early exits. The handling of base cases and the careful use of Python’s slicing capabilities contribute to both correctness and efficiency.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long, colorful train of blocks with letters written on them. This code is a clever helper that looks at that train and tries to break it into smaller pieces. Every time it breaks the train, it checks if the piece you are holding is a special kind of word called a palindrome. A palindrome is a word that reads the same forward and backward, like the name Hannah or the word racecar.

The code starts by looking at the whole train and testing different ways to chop it up. For each chop, it asks if the first part is a palindrome. If the piece is a palindrome, the code remembers it and moves on to look at the rest of the train to see if that can be broken into more palindromes too. It keeps doing this over and over again, trying every possible way to split the letters until it finds all the different combinations where every single piece is a perfect palindrome. Once it has collected all the different ways to group the letters into these special words, it puts them all into a big pile to show you. It is like playing a puzzle game where the goal is to make sure every group of letters is perfectly symmetrical.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.30 | σ = 1.18

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
zfang399 C++
56 links | 41 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Palindrome Partitioning - Backtracking - Leetcode 131'
NeetCode 11 mins
Palindrome Partitioning - Backtracking - Leetcode 131
YouTube video 'Palindrome Partitioning | Backtracking | Khaandani Template | Leetcode 131 | codestorywithMIK'
codestorywithMIK 26 mins
Palindrome Partitioning | Backtracking | Khaandani Template | Leetcode 131 | codestorywithMIK
YouTube video 'Palindrome Partitioning 🔥| Leetcode 131| Backtracking'
Ayushi Sharma 18 mins
Palindrome Partitioning 🔥| Leetcode 131| Backtracking
YouTube video 'Palindrome Partitioning | Live Coding with Explanation | Leetcode #131'
Algorithms Made Easy 7 mins
Palindrome Partitioning | Live Coding with Explanation | Leetcode #131
YouTube video 'Palindrome Partitioning | palindrome partitioning | leetcode 131| dfs'
Naresh Gupta 12 mins
Palindrome Partitioning | palindrome partitioning | leetcode 131| dfs
YouTube video 'LeetCode 131. Palindrome Partitioning Explanation and Solution'
happygirlzt 12 mins
LeetCode 131. Palindrome Partitioning Explanation and Solution
YouTube video '131. Palindrome Partitioning | Recursion | Backtracking | 2 Approaches'
Aryan Mittal 23 mins
131. Palindrome Partitioning | Recursion | Backtracking | 2 Approaches
YouTube video '[Java] Leetcode 131. Palindrome Partitioning [Backtracking #7]'
Eric Programming 12 mins
[Java] Leetcode 131. Palindrome Partitioning [Backtracking #7]
YouTube video 'LeetCode 131. Palindrome Partitioning 中文解释 Chinese Version'
happygirlzt 8 mins
LeetCode 131. Palindrome Partitioning 中文解释 Chinese Version
YouTube video 'Leetcode 131. Palindrome Partitioning | Google Meta) |  Backtracking template | SDE Sheet below'
Coding Decoded 11 mins
Leetcode 131. Palindrome Partitioning | Google Meta) | Backtracking template | SDE Sheet below
YouTube video 'Palindrome Partitioning | Leetcode 131| Live coding session 🔥🔥🔥 | Backtracking'
Coding Decoded 3 mins
Palindrome Partitioning | Leetcode 131| Live coding session 🔥🔥🔥 | Backtracking
YouTube video 'Palindrome Partitioning | Leetcode 131 | Leetcode December Challenge Day 14 | Live coding session'
Coding Decoded 14 mins
Palindrome Partitioning | Leetcode 131 | Leetcode December Challenge Day 14 | Live coding session
YouTube video 'LeetCode 131 Palindrome Partitioning'
Jeevan Kumar - Cracckify 9 mins
LeetCode 131 Palindrome Partitioning
YouTube video 'LeetCode 131. Palindrome Partitioning'
Happy Coding 16 mins
LeetCode 131. Palindrome Partitioning
YouTube video '131. Palindrome Partitioning|| #131|| Leetcode Daily Challenge ||English'
Vishwas aithal 13 mins
131. Palindrome Partitioning|| #131|| Leetcode Daily Challenge ||English
YouTube video '131. Palindrome Partitioning | JavaScript | Backtracking | LeetCode Daily Challenge'
LeetCodeWithMonu 15 mins
131. Palindrome Partitioning | JavaScript | Backtracking | LeetCode Daily Challenge
YouTube video 'Daily Leetcode #1513: May 22, 2024 - 131. Palindrome Partitioning'
Programming Live with Larry 8 mins
Daily Leetcode #1513: May 22, 2024 - 131. Palindrome Partitioning
YouTube video 'Daily Leetcode #1027: Jan 22, 2023 - 131. Palindrome Partitioning'
Programming Live with Larry 7 mins
Daily Leetcode #1027: Jan 22, 2023 - 131. Palindrome Partitioning
YouTube video 'Leetcode 131: Palindrome Partitioning'
Algorithms Casts 14 mins
Leetcode 131: Palindrome Partitioning
YouTube video 'Palindrome Partitioning  (LeetCode 131) (Recursion + Backtracking)'
CodeWithARB 34 mins
Palindrome Partitioning (LeetCode 131) (Recursion + Backtracking)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality