#32
Hard
Dynamic Programming

Longest Valid Parentheses

Find the length of the longest valid parentheses substring.

StringDP

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

1

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.

2

When s[i] is ')', it may connect to either '()' or a longer pattern like '(previous valid segment)'.

3

Name the state in plain language.

4

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

warning

Not checking the matching left index carefully when extending a previous segment.

warning

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.

view_weekBack to the pattern page
LeetCode 32. Longest Valid Parentheses Guide | Interview AiBox