This practice workspace is built for desktop. Open it on a larger screen to start solving.
Longest Valid Parentheses
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
A valid parentheses substring is one where every opening bracket has a matching closing bracket in the correct order.
The classic stack approach pushes -1 as a sentinel base index, then for each '(' pushes its index and for each ')' pops; if the stack becomes empty, push the current index as a new base, otherwise compute i - stack[-1] as a candidate length.
Examples
Constraints
- 0 <= s.length <= 3 * 10^4
- s[i] is '(' or ')'.
Preview Mode
This is a read-only preview of DSAMind's AI coaching. Sign up to get custom feedback on your own solution.
Your approach
- Pattern:Stack
- Time:O(N)
- Space:O(1)
Complete approach — pattern and complexity both named.
Coach
What you got right
You correctly matched the sorted input requirement and implemented a linear-time scan using two pointers.
Where it diverged
No divergence detected. The code correctly aligns with the stated approach.
Next attempt: focus on
Try solving related sliding window problems to build familiarity with two-pointer variants.
Signals
No signals fired — clean run, you stayed in flow.