Minimum Insertions to Balance a Bracket String
Solve this Problems consisting only of '(' and ')', find the minimum number of parentheses that need to be inserted anywhere in the string to make it balancedBalancedEvery '(' has a matching ')' later in the string, and every ')' has a matching '(' earlier — the same property "valid parentheses" checks, just quantified as a repair cost instead of a yes/no..
Unlike checking whether a bracket string is already valid, this asks how far from valid it is. A single running counter does the job in one pass: track how many '(' are currently unmatched. Every ')' either closes one of them (decrement) or, if none are open, is itself unmatched and needs a '(' inserted before it (tally it). Whatever's still open at the very end needs a ')' inserted after it. The total repair cost is exactly the sum of those two kinds of damage — no backtracking or re-scanning required.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ s.length ≤ 10⁴ - ◆
s consists only of the characters '(' and ')'
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Repeatedly Remove Matched Pairs
BruteRepeatedly scan the string for an adjacent "()" pair and remove it, shrinking the string, until no such pair remains anywhere. Whatever's left is exactly the unmatched characters — every leftover ')' needs a '(' inserted before it, and every leftover '(' needs a ')' inserted after it, so the answer is simply the length of what remains. Each pass over the string is O(n), and up to n/2 passes may be needed, so this costs O(n²) overall.
O(n²)O(n)1class Solution {
2 public int minInsertionsToBalance(String s) {
3 while (s.contains("()")) {
4 s = s.replace("()", "");
5 }
6 return s.length();
7 }
8}Optimal — Single Pass With a Running Count
OptimalWalk the string once, tracking how many unmatched '(' are currently "open" with a simple counter (no actual stack needed, since every open bracket is identical). On '(', increment the counter. On ')', close an open bracket if one is waiting (decrement the counter); if none is waiting, this ')' is unmatched, so tally it as a needed insertion. Whatever's still open at the end also needs a closing insertion. The answer is the unmatched-')' tally plus whatever's left open.
O(n)O(1)1class Solution {
2 public int minInsertionsToBalance(String s) {
3 int open = 0, insertions = 0;
4 for (char c : s.toCharArray()) {
5 if (c == '(') {
6 open++;
7 } else {
8 if (open > 0) open--;
9 else insertions++;
10 }
11 }
12 return insertions + open;
13 }
14}