Longest Valid Parentheses
Find the length of the longest valid parentheses substring.
Pattern fit
DP works because the validity at position i can extend a previously solved valid segment if the matching opener is found in the right place.
Key observation
When s[i] is ')', it may connect to either '()' or a longer pattern like '(previous valid segment)'.
Target complexity
O(n) / O(n)
How to break down the solution cleanly
DP works because the validity at position i can extend a previously solved valid segment if the matching opener is found in the right place.
When s[i] is ')', it may connect to either '()' or a longer pattern like '(previous valid segment)'.
Name the state in plain language.
List the decisions that can transition into the state.
Reference implementation
Python# Generic pattern template
# 1D DP
dp = [0] * (n + 1)
dp[0] = base
for i in range(1, n + 1):
dp[i] = transition(dp, i)
# 2D DP
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
dp[i][j] = transition(dp, i, j)
Common pitfalls
Not checking the matching left index carefully when extending a previous segment.
Missing the need to add dp[j-1] for nested valid structures.
Common follow-ups
How would the stack solution compare with the DP solution?
Why is this still O(n) despite extra index checks?
Continue with related problems
Build repeatable depth inside the Dynamic Programming cluster before moving on.