You are given a string s. Write a function to find the length of the longest valid (well-formed) parentheses substring. Please for ((), the answer is (), length 2, for )()()), the answer is ()(), length 4, this is a classic problem that can be solved with a stack or with dynamic programming, and write a function that solves this problem and explain your algorithm.
Assistant
We need to write a function that finds the length of the longest valid parentheses substring. The problem statement: given a string s consisting of '(' and ')', find the length of the longest substring that is a valid (well-formed) parentheses string. Examples: s = "(()" -> answer 2 (the substring "()"); s = ")()())" -> answer 4 (the substring "()()").
We need to provide a solution, explain algorithm, and write function. Possibly in Python? Not specified but common. We'll write a Python function. There are multiple approaches: using stack, DP, two-pass scanning. We'll choose one (maybe stack) and explain.
But we need to ensure we handle edge cases: empty string returns 0, all invalid returns 0, etc.
We'll provide a solution using stack: push indices of '(' onto stack, and push a sentinel -1 at start. When we see ')', pop from stack, then if stack becomes empty, push current index as sentinel; else compute current length as i - stack[-1] and update max_len.
Alternatively DP: dp[i] = length of longest valid substring ending at i. But we'll use stack.
We'll write code:
def longestValidParentheses(s: str) -> int:
max_len = 0
stack = [-1] # base for length calculations
for i, char in enumerate(s):
if char == '(':
stack.append(i)
else: # char == ')'
stack.pop()
if not stack: # stack empty, push current index as new base
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len
Explanation: The stack holds indices of characters that are not part of a valid substring (like unmatched '(') or the base index before start of current valid substring. Initially stack = [-1] to handle cases when first valid substring starts at index 0. When we see '(', we push its index. When we see ')', we pop the matching '(' index (if any). After popping, if stack becomes empty, it means there was no matching '(' and the substring up to current ')' is invalid; we push current index as new base. If stack not empty, then the current valid substring length is i - stack[-1] (where stack[-1] is index of the last unmatched '(' or the base before that). We update max_len.
Complexities: O(n) time, O(n) space in worst case.
We'll also discuss alternative DP approach briefly? Probably not necessary but could mention.
We'll write final answer: explanation and code.
Solution Explanation
We need the length of the longest contiguous substring that forms a valid (well‑formed) parentheses sequence.
The classic linear‑time approach uses a stack that stores indices.
Algorithm (Stack)
Initialize a stack with a single sentinel value -1.
This sentinel marks the position before the start of a potential valid substring.
It allows us to compute lengths that begin at index 0.
Iterate over the string with index i and character c:
If c is '(' → push i onto the stack (it might be matched later).
If c is ')' → pop the top element (which is either a matching '(' or the sentinel).
After popping, if the stack becomes empty, it means the current ')' has no matching '(' in the current segment.
Push the current index i as a new sentinel – this marks the start of the next possible valid substring.
If the stack is not empty, the top element now holds the index of the last unmatched '('or the sentinel that precedes the current valid block.
The length of the valid substring ending at i is i - stack[-1]. Update the maximum length if this is larger.
Return the maximum length found.
Correctness Proof
We prove that the algorithm returns the length of the longest valid parentheses substring.
Lemma 1: At any point, the stack contains indices of characters that are unmatched'(' in the current scanning window, plus one sentinel index that is the position just before the first character of the current potential valid substring.
Proof:
Initially stack = [-1] – the sentinel is before index 0.
When a '(' is seen, its index is pushed and becomes unmatched.
When a ')' is seen, we pop the top.
If the popped element was a '(', that pair is now matched and removed from the set of unmatched '('.
If the popped element was the sentinel, it means there was no '(' to match the current ')'; the sentinel is removed and we push the current index i as the new sentinel (the valid substring cannot cross this point).
Thus the invariant holds after each step. ∎
Lemma 2: Whenever the stack is non‑empty after processing a ')' at index i, the value i - stack[-1] equals the length of the longest valid substring ending exactly at i.
Proof: After popping the matching '(' for this ')', the stack’s top (stack[-1]) is the index of the character just before the current valid block (either an unmatched '(' that cannot be part of the block, or the sentinel). All characters between stack[-1] + 1 and i inclusive are matched correctly (by the invariant that every ')' that finds a '(' reduces the unmatched set). Hence the substring s[stack[-1]+1 … i] is a valid parentheses substring of length i - stack[-1].
Any longer substring ending at i would have to start before stack[-1], but then it would include the character at stack[-1] (which is either an unmatched '(' or a ')' without a partner) and therefore be invalid. So i - stack[-1] is the longest valid substring ending at i. ∎
Lemma 3: The variable max_len is always the length of the longest valid substring encountered so far.
Proof: max_len starts at 0. Each time we compute a candidate length len_cur = i - stack[-1] (by Lemma 2) we set max_len = max(max_len, len_cur). Therefore max_len never decreases and after processing any prefix of the string, it stores the maximum length among all valid substrings ending at positions up to the current index. ∎
Theorem: After processing the entire string, max_len equals the length of the longest valid parentheses substring of s.
Proof: By Lemma 3, after the last character is processed, max_len is the maximum length among all valid substrings that end at any index i in [0, n‑1]. Every valid substring has some ending index, so the global maximum is captured. Hence the returned value is correct. ∎
Complexity Analysis
Time: Each character is processed once, and each index is pushed and popped at most once → O(n) where n = len(s).
Space: The stack stores at most n indices in the worst case (e.g., all '(') → O(n).
Reference Implementation (Python 3)
python
def longestValidParentheses(s: str) -> int:
"""
Returns the length of the longest well‑formed parentheses substring.
"""
max_len = 0
stack = [-1] # sentinel: index before start of a potential block
for i, char in enumerate(s):
if char == '(':
stack.append(i) # push index of '('
else: # char == ')'
# Pop the matching '(' (if any)
stack.pop()
if not stack: # stack became empty → no match for current ')'
stack.append(i) # current index becomes new sentinel
else:
# Length of valid substring ending at i
current_len = i - stack[-1]
max_len = max(max_len, current_len)
return max_len