Problem 237673 · medium · Level 02 Linear Data Structures

Strip Unmatched Brackets

stacks · strings

A string s contains lowercase letters, ( and ). Remove every unmatched bracket and return the result:

  • a ) is unmatched if, reading left to right, there is no earlier ( still waiting for a partner;
  • a ( is unmatched if it never receives a partner by the end of the string.

Letters are always kept.

Examples

Input:  s = "ab)c(d(e)"
Output: "abcd(e)"
Explanation: the ")" at index 2 has no earlier partner and the "(" at index 4 is never closed.

Input:  s = "x(y))(z"
Output: "x(y)z"

Input:  s = ")()("
Output: "()"

Constraints

  • 0 <= len(s) <= 10**5
  • Target: O(n) time

Goals

  • Record the positions of brackets, not just their counts
  • Rebuild a string while skipping a set of indices
Starting Python…