KatInterview

Fewest Brackets to Add for a Balanced String

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsgreedystringsparentheses

Last updated

Count the fewest parenthesis insertions needed to make a string of brackets balanced, using a single left-to-right pass with a running counter.

You are given a string brackets made up only of the characters '(' and ')'. You may insert additional '(' or ')' characters at any positions you like (including the very beginning or end). You may not delete or reorder the existing characters.

A string is balanced if:

  • every '(' is paired with a later ')',
  • every ')' is paired with an earlier, not-yet-paired '(', and
  • the pairs are properly nested.

Return the minimum number of characters that must be inserted so that the resulting string is balanced.

An empty string is balanced, so an empty input needs 0 insertions.

Constraints

  • brackets contains only '(' and ')'.
  • 0 <= len(brackets) <= 10^5.
  • The return value is a single non-negative integer.

Examples

Example 1

Input: min_bracket_insertions('()))((')

Output: 4

Hints

Hint 1

Think about reading the string from left to right and tracking how many opening brackets are still waiting for a partner.

Hint 2

When a closing bracket appears and nothing is waiting, no earlier character can pair with it, so one insertion is unavoidable. Do not let your counter go negative.

Hint 3

Simply comparing the total number of '(' and ')' is not enough, because order matters: consider the string ")(". Add the unavoidable insertions to the openers still unmatched at the end.