Longest Valid Parentheses Problem
Description
LeetCode Problem 32.
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
Constraints:
- 0 <= s.length <= 3 * 10^4
- s[i] is '(', or ')'.
Solution
Approach: Stack of Indices
Checking every substring for validity takes O(n2) time or more. A stack can find the longest valid run in one pass.
Keep a stack of indices. On top are the indices of '(' that are still unmatched. At the bottom is always one index that marks a boundary: the position just before the current valid run (the last unmatched ')', or -1 at the start).
For each index i:
'(': pushi.')': pop. If the stack is now empty, this')'had nothing to match, so it becomes the new boundary: pushi. Otherwise, the substring after the index on top of the stack up toiis valid, so update the answer withi - top.
Example ")()())": the stack starts as [-1]. Index 0 ')' pops -1 and leaves the stack empty, so push 0. Then ( at 1 is pushed and popped by ) at 2, giving length 2 - 0 = 2. The same happens at 3 and 4, giving 4 - 0 = 4. At 5, ')' pops 0 and becomes the new boundary.
The detail that matters is measuring from the index below the matched '(', not from the '(' itself. That way neighboring runs like "()()" or "()(())" are counted as one.
Complexity: O(n) time and O(n) space, where n is the length of s.
class Solution:
def longestValidParentheses(self, s: str) -> int:
# The stack holds indices of unmatched '(' on top of the index of the last unmatched ')'.
# That bottom index (-1 at the start) is the boundary just before the current valid run.
stack = [-1]
longest = 0
for i, ch in enumerate(s):
if ch == "(":
stack.append(i)
else:
stack.pop() # match with the '(' on top, if any
if not stack:
stack.append(i) # unmatched ')': it becomes the new boundary
else:
longest = max(longest, i - stack[-1])
return longest
Now write it from memory
Close the write-up and solve it yourself against the tests.