Longest Valid Parentheses
Given a string s containing only '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
A valid parentheses string follows these rules:
- An empty string is valid.
- If A is valid, then (A) is valid.
- If A and B are valid, then AB is valid.
Return the length of the longest valid parentheses substring.
Example 1
Input
s = "(()"
Output
2
Explanation
The longest valid parentheses substring is:
()
Its length is 2.
Example 2
Input
s = ")()())"
Output
4
Explanation
The longest valid parentheses substring is:
()()
Its length is 4.
Constraints
Hints:
Hint 1
A stack can be used to keep track of unmatched parentheses.
Hint 2
Store indices rather than just the parentheses themselves.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 26, 2026
Last updated
Aug 26, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output