Longest valid parentheses span
Return the length of the longest contiguous well-formed parentheses substring. Input contains only opening and closing parentheses.
unmatched = [-1, 0]
closing_index = 1
unmatched.pop()
print(closing_index-unmatched[-1])Reason about the state
Store unmatched opening indices and a sentinel before the current valid region. An unmatched closing bracket resets the sentinel for later spans. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the length of the longest contiguous well-formed parentheses substring. Input contains only opening and closing parentheses.
The explanation opens here once every check passes.