Algorithm Day91 - Longest Valid Parentheses
🧩 Problem Description
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
💬 Examples
Example 1
1 | Input: s = "(()" |
Example 2
1 | Input: s = ")()())" |
Example 3
1 | Input: s = "" |
💡 Intuition
We want the longest substring that forms valid parentheses. Three common approaches:
- Stack approach: Track indices of unmatched parentheses.
- Dynamic Programming: Use
dp[i]to store the length of longest valid substring ending ati. - Two-pass scanning: Left-to-right and right-to-left counters for balance.
🔢 Java Code (Stack Approach)
1 | class Solution { |
🔢 Java Code (DP Approach)
1 | class Solution { |
⏱ Complexity Analysis
Stack approach:
- Time: O(n)
- Space: O(n)
DP approach:
- Time: O(n)
- Space: O(n)
Two-pass scanning:
- Time: O(n)
- Space: O(1)
✍️ Summary
- Multiple methods exist: stack, DP, or two-pass counting.
- Stack is intuitive and straightforward.
- DP gives structured state-based reasoning.
- Two-pass is space-optimized.
Related problems: lc-20 (Valid Parentheses), lc-22 (Generate Parentheses), lc-301 (Remove Invalid Parentheses).