← Home

1541. Minimum Insertions to Balance a Parentheses String

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
154

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1541. Minimum Insertions to Balance a Parentheses String, the solution in this repository is mainly a stack solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: stack.

The notes already sitting in the source point us in the right direction:

  • Stack

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are minInsertions.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Stack
02/*
03Hint 1: Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'.
04Hint 2: If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer.
05*/
06//Runtime: 108 ms, faster than 100.00% of C++ online submissions for Minimum Insertions to Balance a Parentheses String.
07//Memory Usage: 12.9 MB, less than 50.00% of C++ online submissions for Minimum Insertions to Balance a Parentheses String.
08class Solution {
09public:
10    int minInsertions(string s) {
11        stack<char> stk;
12        
13        int close = 0;
14        int ans = 0;
15        
16        for(char c : s){
17            if(c == ')'){
18                ++close;
19                if(close >= 2){
20                    if(!stk.empty()){
21                        stk.pop();
22                    }else{
23                        ++ans;
24                    }
25                    close -= 2;
26                }
27            }else{
28                //c == '('
29                if(close > 0){
30                    if(!stk.empty() && stk.top() == '('){
31                        ans += (2-close);
32                        stk.pop();
33                    }else{
34                        //add '(' and 2-close ')'
35                        ans += 1 + (2-close);
36                    }
37                    close = 0;
38                }
39                stk.push('(');
40            }
41            // cout << "open: " << stk.size() << ", close: " << close << ", ans: " << ans << endl;
42        }
43        
44        while(close > 0 && !stk.empty()){
45            if(close == 1){
46                close = 0;
47                //add a ')'
48                ++ans;
49            }else{
50                close -= 2;
51            }
52            stk.pop();
53            // cout << "open: " << stk.size() << ", close: " << close << ", ans: " << ans << endl;
54        }
55        
56        if(stk.empty()){
57            //make it even
58            if(close&1){
59                ++close;
60                ++ans;
61            }
62            ans += close>>1;
63        }else{
64            /*
65            if there are k unmatched '(' in stack,
66            we will need k*2 ')'
67            */
68            ans += stk.size() * 2;
69        }
70        
71        return ans;
72    }
73};
74
75//One pass
76//https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/780199/JavaC%2B%2BPython-Straight-Forward-One-Pass
77//Runtime: 84 ms, faster than 100.00% of C++ online submissions for Minimum Insertions to Balance a Parentheses String.
78//Memory Usage: 12.6 MB, less than 50.00% of C++ online submissions for Minimum Insertions to Balance a Parentheses String.
79//time: O(N), space: O(1)
80class Solution {
81public:
82    int minInsertions(string s) {
83        int added = 0, right_to_add = 0;
84        
85        for(char& c : s){
86            if(c == '('){
87                if(right_to_add&1){
88                    //actually add one ')'
89                    ++added;
90                    //so the ')' needed to be added is decreased by one
91                    --right_to_add;
92                }
93                //meet one '(', so we need two more ')'
94                right_to_add += 2;
95            }else{
96                //meet one ')', so need one less ')'
97                --right_to_add;
98                if(right_to_add < 0){
99                    //add one '('
100                    ++added;
101                    /*
102                    because we have added one '(',
103                    we need two more ')'
104                    */
105                    right_to_add += 2;
106                }
107            }
108        }
109        
110        return added + right_to_add;
111    }
112};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.