Minimum Insertions to Balance a Parentheses String (LeetCode 1541): Solution and Explanation

Medium
String
Stack
Greedy

Each '(' must be closed by two adjacent ')'. Count the fewest characters to insert so the whole string is balanced. For (())) the answer is 1, for ))())( it is 3.

Intuition

This is the classic balance check with a twist: a '(' wants two closers, and those two must sit next to each other.

You never need a real stack. Every unfinished '(' owes either two ')' or, if one has already arrived, one. A single counter need holds the total owed.

Two situations force an insertion during the scan. A ')' with nothing to close needs a '(' inserted before it. A '(' arriving while need is odd means the top '(' has a lone ')' that is about to be separated from its partner, so a ')' must be inserted right there. Whatever is still owed at the end is appended.

Approach: One pass with an owed-closer counter

  1. Set need = 0 and res = 0.
  2. On '(': if need is odd, insert a ')' (res += 1, need -= 1). Then add 2 to need.
  3. On ')': subtract 1 from need. If it becomes negative, insert a '(' (res += 1) and set need to 1, since that new '(' still wants one more ')'.
  4. Return res + need.

Step-by-step example

s = "(()))"
  1. Read '(' at 0: need = 2.
  2. Read '(' at 1: need is even, so no fix. need = 4.
  3. Read ')' at 2: need = 3. The inner '(' has one closer.
  4. Read ')' at 3: need = 2. The inner '(' is complete.
  5. Read ')' at 4: need = 1. The outer '(' has one closer.
  6. End: res = 0, need = 1, so the answer is 1 (append one ')').

Code: Python, Java, C++

1class Solution:
2    def minInsertions(self, s: str) -> int:
3        need = 0
4        res = 0
5        for ch in s:
6            if ch == '(':
7                if need % 2 == 1:
8                    res += 1
9                    need -= 1
10                need += 2
11            else:
12                need -= 1
13                if need < 0:
14                    res += 1
15                    need += 2
16        return res + need
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is processed once with constant work.

Space

O(1)

Only the two counters are stored.

Other approaches

Explicit stack of open parentheses (time O(n), space O(n))

Push each '(' and track how many closers it has received. It shows the structure clearly but uses O(n) memory for the same result.

Replace '))' first, then count (time O(n), space O(1))

Scan, treat each adjacent '))' as one closing token and a lone ')' as a closer that needs an inserted ')'. It works but the index handling is easy to get wrong.

Common mistakes

  • Forgetting the odd check on '('. In ()() the first '(' has one ')' and the next '(' splits it, so a ')' must be inserted there, not at the end.
  • Setting need to 0 instead of 1 after inserting a '(' for a stray ')'. The inserted '(' still wants a second ')'.
  • Returning only res. Closers still owed at the end are insertions too.
  • Treating ')' as worth one closer per '(' as in the classic problem.

Frequently asked questions

Why does an odd need mean a split pair?

Each '(' adds 2 and each ')' subtracts 1, so need is odd exactly when the most recent open '(' has received one ')' but not the second. Anything other than ')' next breaks the adjacency.

Is a stack required?

No. The counter captures everything a stack would, because only the top '(' can be half closed.

How does this differ from Minimum Add to Make Parentheses Valid?

There a '(' needs one ')'. Here it needs two adjacent ones, which adds the odd-count fix.