15% off all plans & roadmaps Use code
See plansLeetCode 32 · Solution & editorial
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Longest Valid Parentheses is a Stack Patterns problem, in the Valid Parentheses Matching subpattern. The pattern covers parentheses matching, monotonic stack, histogram, and expression evaluation
Master parentheses validation and balancing using stack. Handle multiple bracket types and minimum additions.
The reference solution runs in O(n) time and O(1) space.
Longest Valid Parentheses has been reported in interviews at Amazon, Facebook, Apple, ByteDance.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Longest Valid Parentheses is a Stack Patterns problem, in the Valid Parentheses Matching subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.