Skip to content
Decoder

Longest Valid Parentheses

Hard

Problem

Given a string s of only ( and ), return the length of the longest contiguous substring that is a well-formed (balanced and properly nested) set of parentheses.

Example 1

Input
s = "(()"
Output
2
Why
"()"

Example 2

Input
s = ")()())"
Output
4
Why
"()()"

Example 3

Input
s = ""
Output
0

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.