KatInterview

Strip Unmatched Brackets From a Text Line

Stacks & QueuesAuto-graded · 23 test cases
MediumAuto-gradedStacks & Queuesstackstringparentheses

Last 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) <= 100000
  • s contains only lowercase letters a-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.