ExamAdda Logo

Longest Valid Parentheses

Hard

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

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

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

ExamAdda Technical Review Team

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.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output