Score of Parentheses
Medium
Topics
Given a balanced parentheses string s, compute its score: () is 1, AB is A+B, and (A) is 2*A.
Example 1
() scores 1, and a wrapped group doubles whatever is inside it. Keeping a running score per depth — pushed on (, folded into its parent on ) — gives 1.Input: s = "()" Output: 1
Example 2
Input: s = "(())" Output: 2
Example 3
Input: s = "()()" Output: 2
Example 4
Input: s = "(()(()))" Output: 6
Constraints
- 2 <= s.length <= 50
- s is a balanced parentheses string.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The grammar has three rules, and the only one that needs memory is (A), which doubles whatever is inside. So carry a running score per nesting level: a stack where each entry is the score accumulated so far at that depth.
Opening a bracket pushes a fresh zero. Closing one pops the inner score v and adds max(2v, 1) to the level below — 2v for the doubling rule, and the 1 covers the base case where v is zero, meaning the brackets were empty and form a bare (). That single max expresses two of the three rules; concatenation is handled by the +=.
Approach
- Start with a stack holding one zero, the score at the outermost level.
- On
(, push 0. - On
), popvand addmax(2v, 1)to the new top. - Return the single remaining entry.
Dry Run
s = "(()(()))"
c stack note
( [0, 0] new frame
( [0, 0, 0] new frame
) [0, 1] inner was 0, so a bare () worth 1
( [0, 1, 0] new frame
( [0, 1, 0, 0] new frame
) [0, 1, 1] inner was 0, so a bare () worth 1
) [0, 3] inner was 1, doubled to 2, added to the 1 already there
) [6] inner was 3, doubled
answer 6
"()" -> 1 "(())" -> 2 "()()" -> 2Complexity
- Time — O(n): one push or pop per character.
- Space — O(n) for the stack, whose depth is the maximum nesting level.
Common Pitfalls
- Writing
2 * vwithout themax, which scores every bare()as 0 and collapses the whole answer to zero. - Writing
max(2 * v, 1)as2 * v + 1. The1is an alternative to the doubling, not an addition to it. - Forgetting to seed the stack with one zero, so the first close has nothing to add into.
- Tracking depth alone and summing
2ⁱper(). That is the neat O(1)-space solution and it is correct, but it only works because every unit of score traces back to a bare()— worth deriving rather than asserting. - Trying to parse into a tree first. The stack of running scores is the parse, done in one pass.
- Assuming the input might be unbalanced. The constraints promise balance, which is why no validation appears.
Full Solution — all languages
class Solution:
def scoreOfParentheses(self, s):
st = [0]
for c in s:
if c == "(":
st.append(0)
else:
v = st.pop()
st[-1] += max(2 * v, 1)
return st[0]import java.util.*;
class Solution {
public int scoreOfParentheses(String s) {
Deque<Integer> st = new ArrayDeque<>();
st.push(0);
for (char c : s.toCharArray()) {
if (c == '(') st.push(0);
else {
int v = st.pop();
st.push(st.pop() + Math.max(2 * v, 1));
}
}
return st.peek();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int scoreOfParentheses(string s) {
vector<int> st = {0};
for (char c : s) {
if (c == '(') st.push_back(0);
else {
int v = st.back();
st.pop_back();
st.back() += max(2 * v, 1);
}
}
return st[0];
}
};/**
* @param {string} s
* @return {number}
*/ var scoreOfParentheses = function(s) {
const st = [0];
for (const c of s) {
if (c === '(') st.push(0);
else {
const v = st.pop();
st[st.length - 1] += Math.max(2 * v, 1);
}
}
return st[0];
};