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

# Remove Invalid Parentheses Python Solution

> Tested Python solution for LeetCode 301 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 301, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), [Backtracking](/catalog/topics/backtracking), [Breadth-First Search](/catalog/topics/breadth-first-search). [View on LeetCode](https://leetcode.com/problems/remove-invalid-parentheses/description/).

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

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

## Problem

Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.

Return *a list of **unique strings*** that are valid with the minimum number of removals. You may return the answer in **any order**.

### Examples

```
Input: s = "()())()"
Output: ["(())()","()()()"]
```

```
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
```

```
Input: s = ")("
Output: [""]
```

### Constraints

* `1 <= s.length <= 25`
* `s` consists of lowercase English letters and parentheses `'('` and `')'`.
* There will be at most `20` parentheses in `s`.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(2^p) over the p <= 20 parenthesis positions, each kept or removed
    # Space: O(n) recursion depth plus the result set
    def remove_invalid_parentheses(self, s: str) -> list[str]:
        rem_left = rem_right = 0
        for ch in s:
            if ch == "(":
                rem_left += 1
            elif ch == ")":
                if rem_left:
                    rem_left -= 1
                else:
                    rem_right += 1

        results: set[str] = set()
        path: list[str] = []
        n = len(s)

        def dfs(i: int, open_count: int, left_rem: int, right_rem: int) -> None:
            if left_rem + right_rem > n - i:
                return
            if i == n:
                if left_rem == 0 and right_rem == 0 and open_count == 0:
                    results.add("".join(path))
                return
            ch = s[i]
            if ch == "(" and left_rem > 0:
                dfs(i + 1, open_count, left_rem - 1, right_rem)
            elif ch == ")" and right_rem > 0:
                dfs(i + 1, open_count, left_rem, right_rem - 1)
            path.append(ch)
            if ch == "(":
                dfs(i + 1, open_count + 1, left_rem, right_rem)
            elif ch == ")" and open_count > 0:
                dfs(i + 1, open_count - 1, left_rem, right_rem)
            elif ch not in "()":
                dfs(i + 1, open_count, left_rem, right_rem)
            path.pop()

        dfs(0, 0, rem_left, rem_right)
        return list(results)
```

## Complexity

| Time | Space |
| - | - |
| O(2^p) over the p \<= 20 parenthesis positions, each kept or removed | O(n) recursion depth plus the result set |

## Tags


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