> ## 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 Python Solution

> Tested Python solution for LeetCode 131 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 131, Medium. Topics: String, Dynamic Programming, Backtracking. [View on LeetCode](https://leetcode.com/problems/palindrome-partitioning/description/).

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

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

## Problem

Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return *all possible palindrome partitioning of `s`*.

### Examples

```
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
```

```
Input: s = "a"
Output: [["a"]]
```

### Constraints

* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(N * 2^N)
    # Space: O(N)
    def partition(self, s: str) -> list[list[str]]:
        result: list[list[str]] = []
        self._backtrack(s, 0, [], result)
        return result

    def _backtrack(self, s: str, start: int, path: list[str], result: list[list[str]]) -> None:
        if start == len(s):
            result.append(path[:])
            return

        for end in range(start + 1, len(s) + 1):
            substring = s[start:end]
            if self._is_palindrome(substring):
                path.append(substring)
                self._backtrack(s, end, path, result)
                path.pop()

    def _is_palindrome(self, s: str) -> bool:
        return s == s[::-1]
```

## Complexity

| Time        | Space |
| ----------- | ----- |
| O(N \* 2^N) | O(N)  |

## Tags

[NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
