#32
Longest Valid Parentheses
HardStringDynamic ProgrammingStackHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Dynamic Programming)★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses dynamic programming to keep track of the lengths of valid parentheses substrings. This method is efficient because it builds on previously computed results, avoiding the need to check every substring.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a DP array of the same length as the input string, filled with zeros.
- 2Step 2: Iterate through the string starting from index 1. For each closing parenthesis, check if it forms a valid pair with an opening parenthesis.
- 3Step 3: If it does, update the DP array based on previous valid lengths to calculate the current valid length.
- 4Step 4: Keep track of the maximum length found during the iteration.
solution.py16 lines
1# Full working Python code with comments
2
3def longest_valid_parentheses(s):
4 max_length = 0
5 dp = [0] * len(s)
6 for i in range(1, len(s)):
7 if s[i] == ')':
8 if s[i - 1] == '(': # Case: '()'
9 dp[i] = (dp[i - 2] if i >= 2 else 0) + 2
10 elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == '(': # Case: '...()'
11 dp[i] = dp[i - 1] + (dp[i - dp[i - 1] - 2] if i - dp[i - 1] >= 2 else 0) + 2
12 max_length = max(max_length, dp[i])
13 return max_length
14
15# Example usage
16print(longest_valid_parentheses('(()')) # Output: 2ℹ
Complexity note: The time complexity is O(n) because we only traverse the string once, and the space complexity is O(n) due to the DP array storing lengths of valid parentheses.
- 1Recognizing that valid parentheses must be balanced and can be checked incrementally helps in optimizing the solution.
- 2Using dynamic programming allows us to build on previously computed results, which is a common pattern in many string-related problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.