← Home

921. Minimum Add to Make Parentheses Valid

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
prefix sumsC++Markdown
921

This is one of those problems where the clean idea matters more than the amount of code. For 921. Minimum Add to Make Parentheses Valid, the solution in this repository is mainly a prefix sums solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. 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: prefix sums.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are minAddToMakeValid.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • 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/**
02Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.
03
04Formally, a parentheses string is valid if and only if:
05
06It is the empty string, or
07It can be written as AB (A concatenated with B), where A and B are valid strings, or
08It can be written as (A), where A is a valid string.
09Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
10
11 
12
13Example 1:
14
15Input: "())"
16Output: 1
17Example 2:
18
19Input: "((("
20Output: 3
21Example 3:
22
23Input: "()"
24Output: 0
25Example 4:
26
27Input: "()))(("
28Output: 4
29 
30
31Note:
32
33S.length <= 1000
34S only consists of '(' and ')' characters.
35**/
36
37/**
38Intuition and Algorithm
39
40Keep track of the balance of the string: the number of '(''s minus the number of ')''s. A string is valid if its balance is 0, plus every prefix has non-negative balance.
41
42The above idea is common with matching brackets problems, but could be difficult to find if you haven't seen it before.
43
44Now, consider the balance of every prefix of S. If it is ever negative (say, -1), we must add a '(' bracket. Also, if the balance of S is positive (say, +B), we must add B ')' brackets at the end.
45
46//class Solution {
47    public int minAddToMakeValid(String S) {
48        int ans = 0, bal = 0;
49        for (int i = 0; i < S.length(); ++i) {
50            bal += S.charAt(i) == '(' ? 1 : -1;
51            // It is guaranteed bal >= -1
52            if (bal == -1) {
53                ans++;
54                bal++;
55            }
56        }
57
58        return ans + bal;
59    }
60}
61
62// meet (): bal: 1->0, ans: 0->0
63// meet ((: bal: 1->2, ans: 0->0
64// meet )): bal: 0 -> 0, ans: 1->2
65// "bal" means remaining "(", "ans" means how many ')' added
66
67Complexity Analysis
68
69Time Complexity: O(N), where N is the length of S.
70
71Space Complexity: O(1). 
72**/
73
74//Your runtime beats 100.00 % of cpp submissions.
75class Solution {
76public:
77    int minAddToMakeValid(string S) {
78        // remove "()" and count remaining '(' or ')'s
79        int remain = S.size();
80        
81        int found = 0;
82        // while((found=S.find("()")) != NULL){//This will give wrong answer!!
83        while((found=S.find("()")) != string::npos){//Must use string::npos!!
84            remain-=2;
85            S.erase(found, 2); //need to delete found () !
86        }
87        return remain;
88    }
89};

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.