AAlgoLoopSpaced repetition for LeetCode
HARDStack / QueueLeetCode ↗

Longest Valid Parentheses

The key idea

Keep a stack of indices and seed it with a -1 base marker. Push the index of every (. On a ), pop one entry: if the stack is now empty, this ) is unmatched, so push its index as the new base; otherwise the current valid run reaches from just past the new top to i, giving length i - stack.top(). The base marker turns a length into a simple index subtraction.

Problem

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

A substring is valid when every '(' has a matching ')' that closes it and the pairs are properly nested. The substring must be contiguous — you cannot skip characters in the middle.

Constraints

Examples

Input: s = "(()" Output: 2
Input: s = ")()())" Output: 4
Input: s = "" Output: 0

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Stack / Queue problems