Palindrome Partitioning II — LeetCode 132 Python Solution

HardStringDynamic Programming
Problem
#132
Reading time
2 min

The problem

Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s.

Example

Input
s = "aab"
Output
1
Explanation
The palindrome partitioning ["aa","b"] could be produced using 1 cut.

Python solution

Python
class Solution:
    def minCut(self, s: str) -> int:
        n = len(s)
        g = [[True] * n for _ in range(n)]
        for i in range(n - 1, -1, -1):
            for j in range(i + 1, n):
                g[i][j] = s[i] == s[j] and g[i + 1][j - 1]
        f = list(range(n))
        for i in range(1, n):
            for j in range(i + 1):
                if g[j][i]:
                    f[i] = min(f[i], 1 + f[j - 1] if j else 0)
        return f[-1]

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 132. Palindrome Partitioning II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 132. Palindrome Partitioning II?
LeetCode 132. Palindrome Partitioning II is rated Hard on LeetCode.
What is the time complexity of LeetCode 132. Palindrome Partitioning II?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 132. Palindrome Partitioning II?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 132. Palindrome Partitioning II cover?
LeetCode 132. Palindrome Partitioning II is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview