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
Longest Valid Parentheses: ")()())")()())Index: 0 1 2 3 4 5Valid: "()()" = 4Invalid: unmatched ')' at start and endValid: middle section "()()" matches properlyOutput: 4
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
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
277.9K Views
High Frequency
~25 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen