Fewest Brackets to Add for a Balanced String
Greedy & IntervalsAuto-graded · 21 test casesLast 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
bracketscontains 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the string once from left to right, keeping a counter waiting of opening brackets that have not yet been paired.
- On
'(', increasewaiting. - On
')':- if
waiting > 0, pair it with a waiting opener and decreasewaiting; - otherwise nothing earlier can pair with it, so we must insert a
'('before it. Increaseadded_open.
- if
After the scan, each opener still in waiting needs a ')' inserted after it. The answer is added_open + waiting.
Why it is correct
There are two independent kinds of problem:
- Unpaired closers: a
')'met when no opener is available. Each one forces its own inserted'('. - Unpaired openers: a
'('never closed by the end of the string. Each one forces its own inserted')'.
Let D be the largest amount by which closers exceed openers over any prefix. Any valid fix needs at least D inserted '(' before that prefix ends. Since the final string must have equal numbers of each bracket, the number of inserted ')' is then determined by the difference in counts, giving a total of at least 2D + (O - C), where O and C are the counts of '(' and ')'. The greedy produces added_open = D and waiting = O - C + D, so its total equals this lower bound and is optimal.
Pairing a ')' with any available opener never hurts, because all waiting openers are interchangeable for later closers.
Edge cases: an empty string gives 0; an already balanced string gives 0; ")(" gives 2 (the counts are equal, but the order makes both characters unpaired).
Complexity
- Time: O(n), one pass.
- Space: O(1), two integer counters.
Reference solution
def min_bracket_insertions(brackets: str) -> int:
waiting = 0 # '(' seen so far that still lack a ')'
added_open = 0 # '(' we must insert for unpaired ')'
for ch in brackets:
if ch == '(':
waiting += 1
elif waiting > 0:
waiting -= 1
else:
added_open += 1
return added_open + waiting