Longest Valid Parentheses

Given a string s containing only the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

A valid parentheses substring is a contiguous substring where every opening parenthesis '(' is matched with a later closing parenthesis ')' in the correct order.

Example 1
Inputs = "(()"
Output2
The longest valid parentheses substring is "()", which has length 2.
Example 2
Inputs = ")()())"
Output4
The longest valid parentheses substring is "()()", which has length 4.

Constraints

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

Asked at 28 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate