Problem Statement
Longest Valid Parentheses
You get a string made only of the characters '(' and ')'. A piece of it is "valid" when every '(' has a matching ')' and the pairs are properly nested, like "()" or "(())". Your job is to find the longest run of characters that is fully valid and return its length. For "(()" the best valid run is "()" near the end, which has length 2.
Signals to notice
Brute force first
Check every substring for validity. Each substring is independently validated, ignoring structure. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Stack-based: push indices onto a stack. When a match is found, compute the length from the current index to the new stack top. Track the maximum length. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on s = ")()())"
init: stack=[-1], max_len=0
i=0 ')': pop -1 -> empty, push 0 -> stack=[0] (new base)
i=1 '(': push 1 -> stack=[0,1]
i=2 ')': pop 1, top=0 -> max_len=max(0,2-0)=2, stack=[0]
i=3 '(': push 3 -> stack=[0,3]
i=4 ')': pop 3, top=0 -> max_len=max(2,4-0)=4, stack=[0]
i=5 ')': pop 0 -> empty, push 5 -> stack=[5] (new base)
return max_len = 4What must stay true
The stack bottom always holds the index just before the start of the current valid segment. When you pop a match, the distance from the current index to the new top gives the valid substring length. As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
stack = [-1]; max_len = 0
for i, c in s:
if c == '(': stack.push(i)
else:
stack.pop()
if stack empty: stack.push(i) # new base index
else: max_len = max(max_len, i - stack.top())
return max_lenPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Resetting the length tracking when you encounter an unmatched ')'. The stack approach handles this naturally — unmatched ')' becomes the new base index. The fix is usually to return to the meaning of each move, not just the steps themselves.