Find the longest well-formed run of brackets. Each ) extends the valid run ending just before its matching (, so one pass of stored lengths works.
▼The problem
LeetCode 32 (Hard). Given a string of ( and ), return the length of the longest valid (well-formed) parentheses substring.
Examples: "(()" → 2 and ")()())" → 4 (LeetCode's), plus the nested "(()())" → 6.
def longest_valid_parentheses(s):
dp = [0] * len(s)
for i in range(1, len(s)):
if s[i] == '(':
continue
if s[i - 1] == '(':
before = dp[i - 2] if i >= 2 else 0
dp[i] = before + 2
else:
j = i - dp[i - 1] - 1
if j >= 0 and s[j] == '(':
before = dp[j - 1] if j >= 1 else 0
dp[i] = dp[i - 1] + 2 + before
return max(dp, default=0)TRY IT ON LEETCODE ▶The solution
def longest_valid_parentheses(s):
dp = [0] * len(s)
for i in range(1, len(s)):
if s[i] == '(':
continue
if s[i - 1] == '(':
before = dp[i - 2] if i >= 2 else 0
dp[i] = before + 2
else:
j = i - dp[i - 1] - 1
if j >= 0 and s[j] == '(':
before = dp[j - 1] if j >= 1 else 0
dp[i] = dp[i - 1] + 2 + before
return max(dp, default=0)Transcript
Longest Valid Parentheses. You get a string of opens and closes. Find the length of the longest stretch that is well-formed: every open closed, in order. It's the harder cousin of Valid Parentheses.
Open, open, close: only the last two match, giving two. Close, open, close, open, close, close: two pairs side by side make four. And open, open, close, open, close, close holds pairs inside a pair: six.
The slow way checks every even-length substring with a counter: plus one for an open, minus one for a close, never below zero, ending at zero. That's n squared substrings, each checked in linear time: n cubed.
The key idea: for each position, remember the longest valid run that ends exactly there. Call it dp of i. An open can never end a run, so it gets zero. A close looks back. If an open sits right before it, they pair: two, plus whatever run ended just before the pair, because runs side by side join up.
If a close sits right before it, that close already has a run. Hop over that run and look just before it. If it's an open, it wraps the run: add two, the inner run, and the run before that open. If not, this close gets zero.
In code, one pass fills dp from left to right, and the answer is the largest entry.
Let's run close, open, close, open, open, close, close, close. The first close has nothing before it: zero. Opens stay zero. The next close pairs with its open: two. Two more opens, then a close pairs: two. The next close sees a close, hops over that pair and finds an open: two, plus two inside, plus the two before: six. The last close hops over all six and lands on a close: zero. The answer is six.
One pass: linear time. One number per character: linear space.
Look back, pair up, add the run before. That's Longest Valid Parentheses.