Longest Valid Parentheses

Hard

Topics
StringDynamic ProgrammingStack

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

Example 1

(0(1)2length 2
The braced run is the longest contiguous valid stretch, length 2. The stack holds indices rather than brackets, and its top is always the last position that could not be matched — so the current run’s length is just the distance back to it. The sentinel -1 is what makes a run starting at index 0 measure correctly.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "(()"
Output: 2

Example 2

)0(1)2(3)4)5length 4
Input:  s = ")()())"
Output: 4

Example 3

empty array
Input:  s = ""
Output: 0

Constraints

  • 0 <= s.length <= 16
  • s[i] is '(' or ')'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The brute force enumerates every substring and validates each with a counter, which is O(n^2) substrings times O(n) to check, so O(n^3). You can shave it to O(n^2) by validating incrementally as you extend each start, but the shape of the problem is still wrong: it keeps re-deciding things it already knows.

The tempting single-pass idea is to sweep with a counter, +1 for ( and -1 for ), and read off runs where the counter returns to zero. That works for "()()" and breaks on "(()", because a counter tells you the balance but not where the valid stretch began. Length is a difference of positions, so positions are what we have to keep.

So keep a stack of indices rather than a count. The useful reframing is that we are not matching brackets, we are tracking the last position that cannot be part of any valid substring — the most recent unmatched character. Call it the base. Every valid run is then measured as i - base.

Seeding the stack with -1 is what makes this uniform. It is a sentinel base meaning "nothing is broken yet", so a string that is valid from the very start measures correctly as i - (-1) = i + 1 with no special case.

The stack holds indices of unmatched ( on top of the current base. On a ) we pop. If the stack is then empty, that ) was itself unmatched, so it becomes the new base. If not, whatever is on top is the boundary of the current valid stretch, and i - top is its length.

Approach

  1. Initialise the stack with -1 and best = 0.
  2. On (, push its index. It is unmatched until proven otherwise.
  3. On ), pop. If the stack is now empty, push i as the new base. Otherwise update best = max(best, i - stack.top()).
  4. Return best.

Note the asymmetry: the stack never stores a ) except as a base. Unmatched closers reset the measurement origin; unmatched openers sit on the stack as boundaries.

Dry Run

s = ")()())", expected answer 4.

i  ch  stack after   action
-   -   [-1]          sentinel base
0   )   [0]           popped -1, stack empty -> this ) is unmatched, new base 0
1   (   [0, 1]        push 1
2   )   [0]           popped 1, top is 0 -> len 2 - 0 = 2, best = 2
3   (   [0, 3]        push 3
4   )   [0]           popped 3, top is 0 -> len 4 - 0 = 4, best = 4
5   )   [5]           popped 0, stack empty -> unmatched, new base 5

answer 4, the substring "()()" at indices 1..4

Watch index 4: the length is measured against base 0, not against the popped index 3. That is what lets two adjacent pairs be counted as one run of 4 rather than two runs of 2 — the single most common place a hand-rolled version goes wrong.

Complexity

  • Time — O(n): one pass, and each index is pushed at most once and popped at most once, so the stack work is O(n) in total. Against the O(n^3) brute force and the O(n^2) incremental version.
  • Space — O(n): the stack. The worst case is a string of all (, such as "(((((", where nothing is ever matched and every index is held at once. Worth knowing that there is an O(1)-space alternative: sweep left-to-right counting opens and closes and record a run whenever they are equal, then sweep right-to-left doing the mirror. Two passes, no stack, same O(n) time — a good answer when the follow-up is "can you do it in constant space?".

Common Pitfalls

  • Not seeding with -1. Then a fully valid string like "()" has nothing to measure against, and the usual patch is an off-by-one that only works for some inputs.
  • Measuring i - popped instead of i - stack.top(). That gives the length of the innermost pair and loses the run, so "()()" reports 2 instead of 4.
  • Pushing the ) index unconditionally rather than only when the stack has emptied. The base must be the last unmatched position.
  • Checking emptiness before popping rather than after. The order is pop first, then ask whether anything is left.
  • Returning the stack size or a count of matched pairs instead of the tracked maximum. The answer is a length in characters, so a run of two pairs is 4, not 2.
  • Forgetting the empty string, which must return 0 — the constraints here allow s.length == 0.

Full Solution — all languages

class Solution:
    def longestValidParentheses(self, s):
        best = 0
        st = [-1]
        for i in range(len(s)):
            if s[i] == '(':
                st.append(i)
            else:
                st.pop()
                if not st:
                    st.append(i)
                else:
                    best = max(best, i - st[-1])
        return best
SensAI
Beta
Tap the mic to stop voice mode