Submissions disabled: This deployment is running in read-only mode for safety. Code execution is not available here.
← Back to all problems
Hard

Longest Valid Parentheses

Updated Jan 31, 2026

Problem

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

Constraints

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

Examples

Example 1

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

Example 2

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

Example 3

Input: s = ""
Output: 0

Function Signature

def longestValidParentheses(self, s: str) -> int

How to Submit

Implement a Solution class with a longestValidParentheses method.

Your method will be called with the input parameters and should return the answer.