Problem 132

Abstract / Summary

Given a string, find the minimum number of cuts needed to split it into palindromic substrings.

Note

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

Python 0132.py

class Solution:
    def minCut(self, s: str) -> int:
        cache = {}
        keyshift = 10_000 # or len(s)

        def isPalindrome(left, right):
            # simple adding @cache causes use of too much memory
            # let's build a caching scheme on our own
            key = left * keyshift + right
            if key in cache:
                return cache[key]

            if left >= right: # one or zero letters
                result = True
            elif s[left] != s[right]:
                result = False
            else:
                result = isPalindrome(left + 1, right - 1)

            cache[key] = result
            return result

        cuts = [ 9999999 ] * len(s) # cuts before index i
        for left in range(len(s)):
            for right in range(left, len(s)):
                if isPalindrome(left, right):
                    if left == 0:
                        cuts[right] = 0 # left border, no cut needed
                    else:
                        cuts[right] = min(cuts[right], cuts[left - 1] + 1)

        return cuts[-1]
32 lines | 1109 bytes | submitted October 7, 2023 | GitHub   24% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • 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 solves the classic palindrome-partitioning problem: given a string s, it returns the minimum number of cuts needed so that every resulting substring is a palindrome. The solution combines a memoized palindrome checker with a dynamic-programming pass that builds the optimal cut count for each prefix of the string.

Core Palindrome Checker

A nested helper function isPalindrome(left, right) determines whether the substring s[left:right+1] reads the same forward and backward. To avoid the overhead of Python’s built-in functools.lru_cache, the code creates its own cache dictionary keyed by a single integer that encodes the pair (left, right). The encoding uses a large multiplier (keyshift) so that each pair maps to a unique key.

def isPalindrome(left, right):
    key = left * keyshift + right
    if key in cache:
        return cache[key]

    if left >= right:                     # one or zero characters
        result = True
    elif s[left] != s[right]:             # mismatch at the ends
        result = False
    else:                                 # shrink inward
        result = isPalindrome(left + 1, right - 1)

    cache[key] = result
    return result

The base case left >= right captures both single-character substrings and empty substrings, guaranteeing that they are treated as palindromes. When the characters at the current ends differ, the function returns False immediately, preventing unnecessary deeper recursion. Otherwise, it recurses on the interior substring, reusing previously cached results whenever possible.

Dynamic Programming for Minimum Cuts

The algorithm maintains an array cuts where cuts[i] stores the minimal number of cuts required for the prefix s[0:i+1]. The array is initialized with a large sentinel value to simplify later min operations.

cuts = [9999999] * len(s)   # sentinel for “infinite” cuts
for left in range(len(s)):
    for right in range(left, len(s)):
        if isPalindrome(left, right):
            if left == 0:
                cuts[right] = 0                     # whole prefix is a palindrome
            else:
                cuts[right] = min(cuts[right],
                                  cuts[left - 1] + 1)  # cut before left

The double loop enumerates every possible substring. When a palindrome is found, the algorithm either sets the cut count to zero (if the palindrome starts at the beginning of the string) or updates cuts[right] with the best known value: the cuts needed for the prefix ending just before left plus one additional cut to separate the palindrome s[left:right+1]. After processing all substrings, cuts[-1] holds the answer for the entire string.

Edge Cases Handled

The palindrome helper treats any substring of length zero or one as a palindrome, which correctly handles strings consisting of a single character and the trivial empty substring that appears during recursion. The outer loop’s condition left == 0 ensures that a palindrome covering the whole prefix requires no cuts, covering the case where the entire input string is already a palindrome. The sentinel value in cuts guarantees that any valid cut count will replace the initial placeholder, even for the first palindrome encountered.

Performance Optimizations

The custom caching scheme replaces the typical decorator-based memoization with a lightweight dictionary lookup keyed by a single integer. By constructing the key as left * keyshift + right, the code avoids storing tuple objects, reducing memory overhead and accelerating cache accesses. The early return on character mismatch (s[left] != s[right]) prevents deeper recursive calls for non-palindromic substrings, cutting down unnecessary work. Initializing cuts with a large constant eliminates the need for conditional checks when updating the minimum, allowing the min function to operate directly on numeric values. Together, these choices keep the algorithm’s runtime practical for moderate-size inputs while staying within Python’s memory constraints.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long piece of paper with letters written on it, and you want to cut it into pieces so that every single piece is a word that reads the same forward and backward.

First, there is a helper tool that checks if a section of the paper is a special word. It remembers the answers it has already found by keeping them in a little notebook so it does not have to check the same letters over and over again.

Then, the program looks at the paper one bit at a time. It searches for every possible way to cut the sections correctly. Every time it finds a way to make a piece, it checks to see if that way uses fewer cuts than the previous ways it discovered. It keeps track of the smallest number of cuts needed for every part of the paper in a list. When it reaches the very end of the string, it hands over the smallest number of cuts it found along the way.

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.11 | σ = 1.37

Complexity Analysis

Time: polynomial
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 Go C# TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
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
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
47 links | 32 authors | 10 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

3 easy 5 medium
9 solutions   October 7, 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