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)
Difficulty
and has an acceptance rate of about 74% (1+ million submissions).
Typical patterns to solve this problem:
- Backtracking
- Dynamic Programming
- String
AI Disclaimer
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.
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
sis an empty string,deeperreturnsNone. This signals that no partition exists, and the caller receives an empty result set. - Single-Character Input - Both
isPalindromeanddeepertreat 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
halfsizeusing 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
deeperskips 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- BothisPalindromeanddeeperare decorated with@cache. This stores the result of each unique call, so repeated evaluations of the same substring avoid recomputation. ForisPalindrome, caching eliminates redundant slice comparisons when the same substring appears in multiple recursive paths. Fordeeper, 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:
- Checks if the current prefix is a palindrome.
- If it is, recursively obtains all partitions of the suffix.
- 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 132: Palindrome Partitioning II
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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