Strip Unmatched Brackets From a Text Line
Stacks & QueuesAuto-graded · 23 test casesLast updated
Delete exactly the brackets that cannot be paired so the remaining text is well-formed, using a single linear scan with a stack or counters.
You are given a string s made of lowercase English letters, opening brackets (, and closing brackets ).
Delete the fewest bracket characters so that the remaining text is well-formed. Return the resulting string. Letters are never deleted, and the surviving characters keep their original relative order.
A string is well-formed if every ( can be paired with a later ), every ) with an earlier (, and the pairs nest properly (equivalently, scanning left to right, the number of ) seen never exceeds the number of ( seen, and the totals are equal at the end).
Which brackets to delete (so the answer is unique).
Pair brackets with the standard nearest-match rule: scan left to right, and each ) pairs with the closest earlier ( that is still unpaired. A ) with no such ( is unpaired. After the scan, every ( that never got a partner is also unpaired. Delete exactly the unpaired brackets and nothing else. The output is the string that remains.
For example, in "(a(b)" the first ( is the unpaired one, so the answer is "a(b)".
Return the resulting string (possibly empty).
Constraints
0 <= len(s) <= 100000scontains only lowercase lettersa-z,(, and).- Target time complexity is linear in
len(s).
Examples
Example 1
Input: strip_unmatched_brackets('lee(t(c)o)de)')
Output: 'lee(t(c)o)de'
Example 2
Input: strip_unmatched_brackets('a)b(c)d')
Output: 'ab(c)d'
Example 3
Input: strip_unmatched_brackets(')((')
Output: ''
Hints
Hint 1
Think about what makes a single bracket impossible to use: a `)` with nothing open before it, or a `(` with nothing left to close it afterwards.
Hint 2
Scan left to right keeping the indices of `(` that are still waiting for a partner. When a `)` arrives, either pair it with the most recent waiting index or mark it for deletion.
Hint 3
After the scan, any indices still waiting are unpaired openers and must also be deleted. Build the answer by skipping all marked indices.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the string once while keeping a stack of indices of ( characters that have not yet found a partner.
- On a letter, do nothing.
- On
(, push its index. - On
), if the stack is non-empty, pop it (the)pairs with the nearest earlier unpaired(). Otherwise this)has nothing to pair with, so mark it for deletion.
After the scan, every index still on the stack is an opener with no later closer, so mark those for deletion too. Finally, build the output from the characters that are not marked.
Why it is correct
- Validity: Every kept
)was paired with an earlier kept(, and every kept(was paired with a later kept). Pairs created by a stack are properly nested, so the result is well-formed. - Minimality: A
)is deleted only when no unpaired(exists before it, so no valid result could use it without deleting something else first. A(is deleted only if no later)was available for it. Because greedy nearest matching maximizes the number of pairs, the number of deleted brackets, which equals the total brackets minus twice the pair count, is the smallest possible. - Uniqueness of the output: The set of unpaired brackets under nearest-match pairing is fixed, so the returned string is deterministic.
Complexity
- Time: O(n), since each character is processed once and the final join is linear.
- Space: O(n) for the stack, the deletion flags, and the output.
Reference solution
def strip_unmatched_brackets(s: str) -> str:
n = len(s)
drop = [False] * n
waiting = [] # indices of '(' that currently have no partner
for i, ch in enumerate(s):
if ch == '(':
waiting.append(i)
elif ch == ')':
if waiting:
waiting.pop()
else:
drop[i] = True
for i in waiting:
drop[i] = True
return ''.join(s[i] for i in range(n) if not drop[i])