Ctrl K

Brackets to Patch In

Medium
A bracket sequence is **balanced** when every opening bracket ( can be matched with a later closing bracket ) so that the pairs nest properly and no bracket is left unmatched. The empty string is balanced too. You are given a string seq made of ( and ). In one step you may insert a single bracket of either kind anywhere in the string. Return the minimum number of insertions that make seq balanced.
Example 1
seq=')(()' → 2

The inner () is already matched. The leading ) lacks an opener and the ( at index 1 lacks a closer, so two brackets are needed, e.g. ()(()).

Example 2
seq='(())()' → 0

The sequence is already balanced, so nothing has to be added.

Example 3
seq='))' → 2

Both closing brackets need a partner, so two ( go in front.

Constraints
  • 1 ≤ seq.length ≤ 1000
  • seq[i] is ( or )
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 MediumOne Bead of Each Color Medium
loading Python…
Input
seq=')(()'
Expected
2

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