Skip to content
Problem 32 · LeetCode 32(opens in a new tab)

Longest Valid Parentheses

HardDynamic programming

You are given a string s made only of the characters "(" and ")". Find the longest stretch of consecutive characters in which the brackets are balanced: every "(" is closed by a later ")", and no ")" closes something that was never opened.

Return the length of that stretch, or 0 if there is none.

Example 1

Input:  s = "())(())"
Output: 4
Why:    "(())" at indices 3 to 6
2 more examples and the constraints

Example 2

Input:  s = "()(()"
Output: 2
Why:    the "(" at index 2 is never closed

Example 3

Input:  s = ")("
Output: 0
Why:    neither bracket has a partner

Constraints

  • 0 ≤ length of s ≤ 30,000
  • Every character is "(" or ")"

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every start, running balanceO(n²)
  2. DP on the run ending at iO(n)
  3. Stack of indicesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30,000 charactersVerdict
Every start, running balanceO(n²)
Correct, too slow
DP on the run ending at iO(n)
Passes; fiddly indices
Stack of indicesO(n)
Best; one pass, easy to explain

n = length of s.

Edge cases to test

  • Empty string. Return 0; the loop never runs.
  • Nothing matches. ")(" or "(((" gives 0.
  • Side by side and nested. "()(())" is one run of 6: the runs join.
  • An unclosed "(" in the middle. "(()(()" gives 2: the "(" at index 3 splits the string, and its index stays in the stack as a wall.

Common mistakes

  • Counting all matched pairs in the string instead of the longest stretch without a break.
  • Forgetting the −1 at the bottom, so a run that starts at index 0 is measured one short or crashes on an empty stack.
  • In the DP, adding dp[j − 1] without checking j ≥ 1.

How to talk through it

  1. 1Clarify. Only round brackets? A substring, so the characters must be next to each other? What for an empty string?
  2. 2Give the brute force. Every start with a running balance; stop when it goes negative. O(n²).
  3. 3Find what breaks a run. An unmatched bracket is a wall. The answer is the widest gap between walls.
  4. 4Code the stack. Keep indices, seed with −1, and measure i − top after each pop. Say what the bottom item means.
  5. 5Test out loud. Run Example 1, "()(())" and the empty string.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?