Ctrl K

Brackets That Close Twice

Medium
In a certain markup an opening bracket is the character (, while a closing bracket is **two ) characters in a row**. A string is well-formed if every ( can be matched with its own )) pair somewhere to its right, and every ) belongs to exactly one such pair. For instance, "())", "(())))" and "())(())))" are well-formed, while ")()", "()))" and "(()))" are not. Given a string text of ( and ) characters, you may insert ( and ) anywhere. Return the fewest insertions that make it well-formed.
Example 1
text="(()" → 3

The inner ( is one ) short and the outer one is two short: "(())))", three insertions.

Example 2
text="())))" → 1

The first )) closes the (, and the second )) needs its own (: "())(())", one insertion.

Example 3
text=")((" → 6

The lone ) needs a ( before it and a ) after it, and the two trailing ( need four more ): 6 in total.

Constraints
  • 1 ≤ len(text) ≤ 10⁵
  • text consists only of ( and )
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Letter Once MediumErase Digits for the Smallest Number MediumSmallest Up-Down Sequence MediumBrackets With Wildcards MediumBrackets to Patch In Medium
loading Python…
Input
text="(()"
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 118 tests on the server, hidden ones included.