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 INPUT String s = ")()())" 0 1 2 3 4 5 ) ( ) ( ) ) Valid pair Unmatched Stack-based approach Stack stores indices of unmatched '(' and boundary markers -1 Initial boundary ALGORITHM STEPS 1 Initialize Stack Push -1 as boundary 2 Process '(' Push index to stack 3 Process ')' Pop, if empty push i else calc: i - top 4 Track Maximum Update max length Execution Trace: i=0 ')': pop, empty-->push 0 i=1 '(': push 1 i=2 ')': pop, len=2-0=2 i=3 '(': push 3 i=4 ')': pop, len=4-0=4 i=5 ')': pop, empty-->push 5 FINAL RESULT Longest Valid Substring: ) ( ) ( ) ) "()()" = 4 chars OUTPUT 4 OK Time: O(n) Space: O(n) Single pass solution Key Insight: The stack stores indices of unmatched '(' and boundary markers. When we find a ')', we pop and calculate the valid length as current_index - stack_top. If stack becomes empty after pop, we push current index as new boundary. This elegantly handles nested and consecutive valid parentheses. TutorialsPoint - Longest Valid Parentheses | Optimal Solution (Stack-based O(n))
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