Longest Valid Parentheses
LeetCode 32 | Difficulty: Hardβ
HardProblem Descriptionβ
Given a string containing just the characters '(' and ')', return 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 `')'`.
Topics: String, Dynamic Programming, Stack
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
Stackβ
Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.
Matching brackets, next greater element, evaluating expressions, backtracking history.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 72 ms)β
| Metric | Value |
|---|---|
| Runtime | 72 ms |
| Memory | 23.2 MB |
| Date | 2020-01-12 |
public class Solution {
public int LongestValidParentheses(string s) {
Stack<int> stack = new Stack<int>();
int result = 0;
for (int i = 0; i < s.Length; i++)
{
if(s[i] == '(')
{
stack.Push(i);
}
else if(stack.Count >0 && s[stack.Peek()] == '(')
{
stack.Pop();
int validLen = stack.Count == 0 ? i+1 : i- stack.Peek();
result = Math.Max(result, validLen);
}
else
{
stack.Push(i);
}
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Dynamic Programming | $O(n)$ | $O(n)$ |
| Stack | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Break the problem into smaller subproblems. Communicate your approach before coding.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.
- Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?