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

# Longest Valid Parentheses Python Solution

> Tested Python solution for LeetCode 32 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 32, Hard. Topics: String, Dynamic Programming, Stack. [View on LeetCode](https://leetcode.com/problems/longest-valid-parentheses/description/).

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

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

## Problem

Given a string containing just the characters `'('` and `')'`, return the length of the longest valid (well-formed) parentheses *substring*.

### Examples

```
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
```

```
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
```

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

### Constraints

* 0 \<= s.length \<= 3 \* 10^4
* `s[i]` is `'('`, or `')'`.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def longest_valid_parentheses(self, s: str) -> int:
        max_length = 0
        # Stack of indices; seeded with -1 as the last "unmatched" position
        stack: list[int] = [-1]

        for i, char in enumerate(s):
            if char == "(":
                stack.append(i)
            else:
                stack.pop()
                if not stack:
                    # Unmatched ')', reset the base index
                    stack.append(i)
                else:
                    max_length = max(max_length, i - stack[-1])

        return max_length
```

## Complexity

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

## Tags

[Grind](/catalog/grind).
