Score of Parentheses (LeetCode 856): Solution and Explanation
Score a balanced parentheses string where () is 1, two balanced strings side by side add, and wrapping a balanced string in parentheses doubles it.
Intuition
The rules describe a tree: every pair of parentheses is a node, and the pairs directly inside it are its children. A leaf () is worth 1, and any other pair is worth twice the sum of its children.
We do not need to build that tree. Reading left to right, an open parenthesis starts a new node with a running total of 0, and a close parenthesis finishes the most recent unfinished node. That is exactly a stack.
When a pair closes we know its inner total v. If v is 0 the pair was a bare () and is worth 1; otherwise it is worth 2 * v. That value belongs to the parent, so it is added to the new top of the stack.
Starting the stack with a single 0 gives the outermost level a place to collect top-level pairs that sit side by side. At the end that value is the answer.
Approach: Stack of running scores, one per open level
- Start with
stack = [0]. - On
(, push 0 for the new level. - On
), pop the inner scorevand addmax(2 * v, 1)to the new top. - After the scan, return the one value left on the stack.
Step-by-step example
s = "()"
- Start: stack = [0].
- '(' opens depth 1: push 0, stack = [0, 0].
- ')' closes it: pop v = 0. A bare pair is worth 1, so the outer level becomes 1. Stack = [1].
- Return 1.
Code: Python, Java, C++
1class Solution:
2 def scoreOfParentheses(self, s: str) -> int:
3 stack = [0]
4 for c in s:
5 if c == '(':
6 stack.append(0)
7 else:
8 v = stack.pop()
9 stack[-1] += max(2 * v, 1)
10 return stack.pop()1class Solution {
2 public int scoreOfParentheses(String s) {
3 Deque<Integer> stack = new ArrayDeque<>();
4 stack.push(0);
5 for (char c : s.toCharArray()) {
6 if (c == '(') {
7 stack.push(0);
8 } else {
9 int v = stack.pop();
10 stack.push(stack.pop() + Math.max(2 * v, 1));
11 }
12 }
13 return stack.pop();
14 }
15}1class Solution {
2public:
3 int scoreOfParentheses(string s) {
4 vector<int> st{0};
5 for (char c : s) {
6 if (c == '(') {
7 st.push_back(0);
8 } else {
9 int v = st.back();
10 st.pop_back();
11 st.back() += max(2 * v, 1);
12 }
13 }
14 return st.back();
15 }
16};Time and space complexity
O(n)
Each character causes one push or one pop plus one addition.
O(n)
The stack grows with the nesting depth, which is at most n / 2. The counting alternative below uses O(1) space.
Other approaches
Count the cores (time O(n), space O(1))
Only the innermost () pairs contribute, each worth 2^depth where depth is the number of open parentheses around it. Walk the string with a depth counter and add 1 << depth whenever a ) directly follows a (.
Recursive divide and conquer (time O(n^2) worst case, space O(n))
Split the string into top-level balanced parts, score each part as 1 for () or twice the score of its inside, and add them. Easy to write but can rescan the string at every depth.
Common mistakes
- Forgetting the base 0 on the stack. Without it, a string like
()()has no level to collect the second pair, and the final pop fails. - Writing
2 * vwithout themax(..., 1). An empty pair has v = 0 and must be worth 1, not 0. - Adding the pair value to the popped level instead of the level below it. The pair belongs to its parent.
- Using a bit shift without bounds in the counting method. Depth reaches at most 25 here, so 2^24 still fits in a 32-bit int.
Frequently asked questions
Why max(2 * v, 1)?
It merges the two rules in one expression. If nothing was inside the pair, v is 0 and the pair is () worth 1. If something was inside, the pair doubles it, and 2 * v is at least 2, so max picks it.
Can the answer overflow?
No. With at most 50 characters, the deepest nesting is 25 levels, giving 2^24 = 16,777,216, well inside a 32-bit int.
Is there an O(1) space solution?
Yes. Each innermost () contributes 2 to the power of the depth around it, so a depth counter and a running sum are enough. The stack version is easier to derive from the rules, which is why many people present it first.