← Home

856. Score of Parentheses

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

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 856. Score of Parentheses, the solution in this repository is mainly a stack solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are scoreOfParentheses, F.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • 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^2), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Score of Parentheses.
02//Memory Usage: 6 MB, less than 100.00% of C++ online submissions for Score of Parentheses. 
03class Solution {
04public:
05    int scoreOfParentheses(string S) {
06        stack<int> stk;
07        for(char c : S){
08            // cout << c << " " << stk.size() << endl;
09            switch(c){
10                case '(':
11                    //use -1 to represent '('
12                    stk.push(-1);
13                    break;
14                case ')':
15                    //stk.size() must > 0
16                    if(stk.top() == -1){
17                        stk.pop();
18                        stk.push(1);
19                    }else{
20                        int tmp = 0;
21                        while(stk.top() != -1){
22                            tmp += stk.top(); stk.pop();
23                        }
24                        stk.pop(); //'('
25                        stk.push(tmp * 2);
26                    }
27                    break;
28            }
29        }
30        
31        int ans = 0;
32        while(!stk.empty()){
33            ans += stk.top(); stk.pop();
34        }
35        return ans;
36    }
37};
38
39//Approach 1: Divide and Conquer
40//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Score of Parentheses.
41//Memory Usage: 6.2 MB, less than 100.00% of C++ online submissions for Score of Parentheses.
42//time: O(N^2), space: O(N)
43class Solution {
44public:
45    int F(string S, int start, int end){
46        //end is exclusive
47        int ans = 0, balance = 0;
48        
49        for(int i = start; i < end; i++){
50            balance += (S[i] == '(') ? 1 : -1;
51            if(balance == 0){
52                if(i - start == 1){
53                    //')' 's mathcing '(' is its previous char
54                    ans++;
55                }else{
56                    //')' matches to the '(' far before
57                    ans += 2 * F(S, start+1, i);
58                }
59                //the start position of new '('
60                start = i+1;
61            }
62        }
63        
64        return ans;
65    };
66    
67    int scoreOfParentheses(string S) {
68        return F(S, 0, S.size());
69    }
70};
71
72//Approach 2: Stack
73//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Score of Parentheses.
74//Memory Usage: 6.1 MB, less than 100.00% of C++ online submissions for Score of Parentheses.
75//time: O(N), space: O(N)
76class Solution {
77public:
78    int scoreOfParentheses(string S) {
79        stack<int> stk;
80        stk.push(0);
81        
82        for(char c : S){
83            if(c == '('){
84                stk.push(0);
85            }else{
86                int v = stk.top(); stk.pop();
87                int w = stk.top(); stk.pop();
88                //max(2*v, 1): v could be 
89                /*
90                if v is 0, a.k.a. last char is '(',
91                then score becomes 1
92                else if v is not 0
93                then use score specified by v
94                */
95                stk.push(w + max(2*v, 1));
96                // cout << v << " " << w << " " << w + max(2*v, 1) << endl;
97            }
98        }
99        
100        return stk.top();
101    }
102};
103
104//Approach 3: Count Cores
105//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Score of Parentheses.
106//Memory Usage: 6.2 MB, less than 100.00% of C++ online submissions for Score of Parentheses. 
107//time: O(N), space: O(1)
108class Solution {
109public:
110    int scoreOfParentheses(string S) {
111        int ans = 0, balance = 0;
112        
113        for(int i = 0; i < S.size(); i++){
114            if(S[i] == '('){
115                balance++;
116            }else{
117                balance--;
118                if(S[i-1] == '('){
119                    ans += (1 << balance);
120                }
121            }
122            // cout << balance << " " << ans << endl;
123        }
124        
125        return ans;
126    }
127};

Cost

Complexity

Time
O(N^2), space: O(N)
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.