Minimum Insertions to Balance a Parentheses String (LeetCode 1541): Solution and Explanation
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
- Set
need = 0andres = 0. - On '(': if
needis odd, insert a ')' (res += 1,need -= 1). Then add 2 toneed. - On ')': subtract 1 from
need. If it becomes negative, insert a '(' (res += 1) and setneedto 1, since that new '(' still wants one more ')'. - Return
res + need.
Step-by-step example
s = "(()))"
- Read '(' at 0: need = 2.
- Read '(' at 1: need is even, so no fix. need = 4.
- Read ')' at 2: need = 3. The inner '(' has one closer.
- Read ')' at 3: need = 2. The inner '(' is complete.
- Read ')' at 4: need = 1. The outer '(' has one closer.
- 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 + need1class Solution {
2 public int minInsertions(String s) {
3 int need = 0;
4 int res = 0;
5 for (char ch : s.toCharArray()) {
6 if (ch == '(') {
7 if (need % 2 == 1) {
8 res++;
9 need--;
10 }
11 need += 2;
12 } else {
13 need--;
14 if (need < 0) {
15 res++;
16 need += 2;
17 }
18 }
19 }
20 return res + need;
21 }
22}1class Solution {
2public:
3 int minInsertions(string s) {
4 int need = 0;
5 int res = 0;
6 for (char ch : s) {
7 if (ch == '(') {
8 if (need % 2 == 1) {
9 res++;
10 need--;
11 }
12 need += 2;
13 } else {
14 need--;
15 if (need < 0) {
16 res++;
17 need += 2;
18 }
19 }
20 }
21 return res + need;
22 }
23};Time and space complexity
O(n)
Each character is processed once with constant work.
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.