> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Palindrome Partitioning II Python Solution

> Tested Python solution for LeetCode 132 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 132, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), [Dynamic Programming](/catalog/topics/dynamic-programming). [View on LeetCode](https://leetcode.com/problems/palindrome-partitioning-ii/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 132   # by problem number
lcpy gen -s palindrome_partitioning_ii   # by problem name
```

## 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`*.

### Examples

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

```
Input: s = "a"
Output: 0
```

```
Input: s = "ab"
Output: 1
```

### Constraints

* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters only.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/palindrome_partitioning_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/palindrome_partitioning_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2)
    # Space: O(n^2)
    def min_cut(self, s: str) -> int:
        n = len(s)
        is_pal = [[False] * n for _ in range(n)]
        cut = [0] * n
        for i in range(n):
            best = n
            for j in range(i + 1):
                if s[j] == s[i] and (i - j < 2 or is_pal[j + 1][i - 1]):
                    is_pal[j][i] = True
                    best = 0 if j == 0 else min(best, cut[j - 1] + 1)
            cut[i] = best
        return cut[n - 1]
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) | O(n^2) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.