Longest Valid Parentheses

50 min · longestValidParentheses()

One stray parenthesis can split a long string into several smaller islands of valid structure.

You're given a string s containing only ( and ). Return the length of its longest contiguous substring — one unbroken run of characters — that is well-formed: every opening parenthesis has a later closing partner, and pairs close in the reverse order they opened.

A few ground rules:

  • You may start and stop anywhere in s, but you can't skip characters inside the run.
  • Unmatched parentheses outside the chosen run don't matter.
  • Length counts characters, so every nonzero answer is even.
  • The empty string has answer 0.

Constraints

  • 0 <= s.length <= 100_000
  • s consists only of ( and ).

Hints

Measure one starting point

Pick a start and scan right with a balance: ( adds one and ) subtracts one. A zero balance marks a valid candidate; a negative balance means this start can never recover.

Keep the unmatched positions

Store indices of unmatched opening parentheses. When a closing parenthesis arrives, match it by popping. The index now on top tells you where the current valid run began.

Give the stack a base

Begin with -1 as the boundary before the string. If a closing parenthesis has nothing to match, its own index becomes the new boundary. Otherwise the current valid length is i - stack[-1].

Follow-up

Can you reach O(1) extra space by counting opens and closes left-to-right, then repeating the scan right-to-left to catch the imbalance the first direction misses?

Visible cases

Examples

Example 1

ready
Input
s = "(()"
Expected
2
Why
the first opening and the closing parenthesis form a length-2 run

Example 2

ready
Input
s = ")()())"
Expected
4
Why
the middle run ()() is well-formed and has length 4

Example 3

ready
Input
s = ""
Expected
0
Why
an empty string contains no nonempty valid run

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite