Longest Valid Parentheses - Problem
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
A valid parentheses substring means every opening parenthesis has a corresponding closing parenthesis in the correct order, with no unmatched parentheses.
Examples:
"(()": longest valid substring is "()" with length 2")()())": longest valid substring is "()()" with length 4"": empty string returns 0
Input & Output
Example 1 — Mixed Valid and Invalid
$
Input:
s = ")()())"
›
Output:
4
💡 Note:
The longest valid parentheses substring is "()()", which has length 4. It appears in the middle of the string.
Example 2 — Simple Valid Pair
$
Input:
s = "(()"
›
Output:
2
💡 Note:
The longest valid parentheses substring is "()", which has length 2.
Example 3 — Empty String
$
Input:
s = ""
›
Output:
0
💡 Note:
An empty string contains no valid parentheses, so the length is 0.
Constraints
- 0 ≤ s.length ≤ 3 × 104
- s[i] is '(' or ')'.
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
String with opening '(' and closing ')' parentheses
2
Find Valid Substrings
Identify all properly matched parentheses
3
Return Maximum Length
Length of longest valid substring found
Key Takeaway
🎯 Key Insight: Track lengths of valid parentheses ending at each position to build up the solution efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code