hardDynamic ProgrammingStackDynamic Programming

Longest Valid Parentheses

hardTime: O(n)Space: O(n)

Recognize the pattern

longest valid parentheses substringnesting depth trackingmultiple valid segments

Brute force idea

A straightforward first read of Longest Valid Parentheses is this: 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.

Better approach

A calmer way to see Longest Valid Parentheses is this: 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.

Key invariant

The compass for Longest Valid Parentheses is this: 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.

Watch out for

One easy way to drift off course in Longest Valid Parentheses is this: 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.

Dynamic Programming Pattern