Longest Well-Formed Bracket Run
Stacks & QueuesAuto-graded · 29 test casesLast updated
Find the length of the longest contiguous well-formed stretch in a string of only round brackets, testing stack-based index tracking and handling of unmatched characters.
You receive a string text made up solely of the characters ( and ).
Call a string well-formed if it follows these rules:
- The empty string is well-formed.
- If
Xis well-formed, then wrapping it as(X)gives a well-formed string. - If
XandYare both well-formed, then writing them side by side asXYgives a well-formed string.
Your task is to find the longest contiguous piece of text that is well-formed, and return its length. If no non-empty piece of text is well-formed, return 0.
Notes
- A piece must be a run of consecutive characters. You may not skip characters.
- Only the length is returned, so it does not matter which piece you pick when several pieces tie for the longest.
- An empty input string yields
0.
Constraints
0 <= len(text) <= 30000- Each character of
textis either(or).
Examples
Example 1
Input: longest_wellformed_run(')(())()')
Output: 6
Example 2
Input: longest_wellformed_run('()(()')
Output: 2
Example 3
Input: longest_wellformed_run('))((')
Output: 0
Hints
Hint 1
Any well-formed piece ends at some `)`. Think about how to compute, for each position, how far to the left a well-formed piece ending there can reach.
Hint 2
Keep a stack of indices rather than characters. Seed it with `-1` so that a well-formed prefix can be measured the same way as any other piece.
Hint 3
On a `)`, pop first. If the stack is now empty, this `)` is unmatched: push its index as a new left boundary. Otherwise the current length is `i - stack[-1]`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every well-formed substring ends at some ). So if, for each index i, we can determine the length of the longest well-formed substring ending exactly at i, the answer is the maximum over all i.
We use a stack of indices:
- The bottom entry is a boundary: the index of the most recent
)that found no partner, or-1if there has been none yet. - Entries above it are the indices of
(characters that are still unmatched.
Processing each character:
- On
(, push its index. - On
), pop the top.- If the stack is still non-empty, this
)matched a(. The new top is the nearest unmatched position to the left, and everything strictly between it andiis well-formed, so the candidate length isi - stack[-1]. - If the stack is now empty, we popped the boundary, meaning this
)is unmatched. No well-formed substring can span it, so pushias the new boundary.
- If the stack is still non-empty, this
Why it is correct
After handling index i, every index on the stack is unmatched within the prefix text[0..i], and all characters between consecutive stack entries are matched among themselves.
When a ) at i is matched and t is the new top:
text[t+1..i]contains no unmatched characters, so every bracket in it is paired inside it with proper nesting; it is well-formed.- It cannot be extended left. If
tis a boundary)(or-1), any substring containing it has a prefix with more)than(, so it is not well-formed. Iftis an unmatched(, then a well-formed substring starting atj <= tand ending atiwould requiretext[j..t-1]to have negative net balance, but it is a prefix of a well-formed string and must have non-negative balance, a contradiction.
So the value i - t is exactly the longest well-formed substring ending at i, and the maximum over all i is the answer. Concatenations like ()() are handled automatically because the length is measured back to the boundary, not to the popped (.
Complexity
- Time: O(n); each index is pushed and popped at most once.
- Space: O(n) in the worst case (for example, a string of only
().
An O(1)-space alternative uses two counters in a left-to-right pass (record 2 * open when counts are equal, reset when close > open) and a mirrored right-to-left pass.
Reference solution
def longest_wellformed_run(text: str) -> int:
# The stack's bottom is a boundary: the index of the last unmatched ')',
# or -1 if none exists. Above it sit indices of '(' still awaiting a match.
stack = [-1]
best = 0
for i, ch in enumerate(text):
if ch == '(':
stack.append(i)
else:
stack.pop()
if stack:
length = i - stack[-1]
if length > best:
best = length
else:
# Unmatched ')': becomes the new boundary.
stack.append(i)
return best