iq.lab
Python starts when a code cell comes near or you run one
mediumStack target 25 min

Remove the fewest parentheses

A string s holds lowercase letters and the round brackets ( and ). Delete as few brackets as possible so that the brackets left are balanced: each ) closes an earlier (, and each ( is closed by a later ). In counting terms: reading left to right, the ) never outnumber the ( so far, and at the end the two counts are equal.

Keep every letter, keep the characters that remain in their original order, and return the resulting string. When several strings need the same smallest number of deletions, return any one of them. A string with no brackets, including the empty string, is already balanced.

Example 1
Inputs = "ab)c(d"Output"abcd"

The ) has no ( before it, and the ( has no ) after it. Both go.

Example 2
Inputs = "x(y)z)"Output"x(y)z"

One deletion is needed. Deleting the first ) instead gives "x(yz)", which is also accepted.

Example 3
Inputs = "))(("Output""

No bracket can be paired, so all four go.

Constraints
  • 0 ≤ len(s) ≤ 105

  • Every character is a lowercase letter, ( or ).

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.