Score of Parentheses solution explained

Score of Parentheses asks you to score a balanced string of brackets where an empty pair "()" is worth 1, two balanced strings side by side add up, and wrapping a balanced string in a pair doubles it. A stack of running scores solves it in one pass: push 0 for every opening bracket, and on every closing bracket pop the inner score and add either 1 (if it was empty) or double the inner score to the level below. A neater observation, that each "()" contributes 2 to the power of its depth, gets space down to O(1).

By Published 7 min read

Restating the problem

You get a non-empty string made only of "(" and ")" in which every bracket is properly matched. Give it a score using three rules: a pair with nothing inside scores 1; two balanced strings written one after the other score the sum of their scores; and a balanced string wrapped in one more pair scores twice what it scored on its own. Return the score of the whole string.

"()()()"     ->  3    1 + 1 + 1
"(()())"     ->  4    2 × (1 + 1)
"((()))()"   ->  5    2 × 2 × 1, plus 1
"(()((())))" ->  10   2 × (1 + 2 × 2 × 1)
Strings made up for this page, with their scores

What it tests

The problem checks whether you can turn a recursive definition into an iterative process. Many candidates write a correct recursive solution and then get asked for something linear, or for constant space. The best answers move from the definition, to the stack, to the depth observation, and explain why each step still follows the rules.

Straight from the definition: recursion

Split the string into its top-level balanced pieces by tracking depth: a piece ends whenever the depth returns to zero. A piece that is exactly "()" scores 1; any other piece is a pair wrapped around a smaller balanced string, so it scores twice the score of its inside. Add the pieces. This mirrors the rules exactly, but deep nesting makes it rescan the same characters at every level, which is quadratic for a string like "((((...))))", and very deep inputs can hit the recursion limit.

def score_slow(s):
    total, depth, start = 0, 0, 0
    for i, ch in enumerate(s):
        depth += 1 if ch == "(" else -1
        if depth == 0:                     # s[start..i] is one balanced piece
            inner = s[start + 1:i]
            total += 1 if inner == "" else 2 * score_slow(inner)
            start = i + 1
    return total
Python: split into top-level pieces and recurse. O(n squared) for deep nesting.

One pass with a stack of scores

Think of each open bracket as starting a new level whose score begins at 0. Keep one entry per open level on a stack, with an extra entry at the bottom for the top level of the string. When a ")" closes the current level, pop its score v. If v is 0, the pair was empty and is worth 1; otherwise it wraps something worth v, so it is worth 2v. Either way, add that value to the level below, because pieces side by side add up. At the end, the bottom entry is the answer.

def score_of_parentheses(s):
    stack = [0]                     # score of the outermost level
    for ch in s:
        if ch == "(":
            stack.append(0)
        else:
            inner = stack.pop()
            stack[-1] += max(2 * inner, 1)
    return stack[0]
Python: one running score per open level

Constant space: count depth

Unroll the rules and a pattern appears. Only the empty pairs "()" create value. Every pair around one of them doubles it, so an empty pair sitting inside d other pairs contributes 2 to the power of d, and the total is the sum over all empty pairs. You can find them in one scan: an empty pair is a ")" right after a "(". Track depth as you go, and when you see such a ")", add 2^depth using the depth after closing it.

function scoreOfParentheses(s) {
  let depth = 0;
  let score = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] === "(") {
      depth++;
    } else {
      depth--;
      if (s[i - 1] === "(") score += 2 ** depth; // an empty pair at this depth
    }
  }
  return score;
}
JavaScript: add 2^depth for every "()"

Using 2 ** depth instead of 1 << depth avoids the 32-bit limit of JavaScript's shift operator. Scores still grow fast with depth, so for very deep strings ask what range the answer must fit in.

Tracing "(()((())))"

Stack version, bottom of the stack on the left
CharActionStack after
(open level0, 0
(open level0, 0, 0
)pop 0, add 1 below0, 1
(open level0, 1, 0
(open level0, 1, 0, 0
(open level0, 1, 0, 0, 0
)pop 0, add 1 below0, 1, 0, 1
)pop 1, add 2 below0, 1, 2
)pop 2, add 4 below0, 5
)pop 5, add 10 below10
Stack version, bottom of the stack on the left. Scroll sideways on a small screen.

The depth method agrees: the first "()" sits inside one pair (2^1 = 2) and the second inside three pairs (2^3 = 8), for a total of 10.

Complexity

n is the length of the string
ApproachTimeExtra space
Recursion on top-level piecesO(n squared) for deep nestingO(n) for recursion and slices
Stack of running scoresO(n)O(n)
Depth count, 2^depth per empty pairO(n)O(1)
n is the length of the string. Scroll sideways on a small screen.

Inputs that catch bugs

  • A single pair "()": the answer is 1, not 2.
  • Long flat runs like "()()()()": every pair is at depth 0 and worth 1.
  • Deep nesting like "(((())))": only one empty pair, worth 2^3 = 8.
  • Mixed shapes like "(()((())))": side-by-side pieces inside a wrapper add before the wrapper doubles them.
  • Very deep strings: recursion depth in the first method, and integer range in every method.

Common mistakes

  • Doubling an empty pair, which gives 2 for "()". The max(2v, 1) handles this.
  • Starting the stack empty, so the final pop has nowhere to add its value.
  • In the depth method, using the depth before closing the bracket, which doubles every contribution.
  • Counting every closing bracket instead of only those right after an opening one.
  • Assuming the input might be unbalanced and adding checks that clutter the answer; ask, and state the assumption.

Variations

  • Validate first: if the string might be unbalanced, run the Valid Parentheses check before scoring.
  • Several bracket types with different multipliers: keep the stack version and multiply by the factor for the closing type.
  • Maximum nesting depth: the same depth counter, tracking its largest value.
  • Arithmetic instead of brackets: Basic Calculator II evaluates an expression with the same push-and-combine rhythm.

How to explain it out loud

Fictional example

From the stack to the depth shortcut
Candidate
Each open bracket starts a new level, so I keep a stack with one running score per level. When a level closes, it is worth 1 if it was empty or double its contents, and I add that to the level below.
Interviewer
Can you avoid the stack?
Candidate
Only empty pairs create value, and each enclosing pair doubles it. So an empty pair at depth d is worth 2 to the d. I scan once, track depth, and whenever a closing bracket follows an opening one, I add 2 to the depth after closing.
Candidate
Both are linear; the second needs constant space.

In this batch, Basic Calculator II also folds values into the top of a stack, and Longest Absolute File Path tracks a running total per depth level. Remove Duplicate Letters is a harder stack problem where popping has conditions.

Practice with Natively

Interviewers often push for the constant-space version here, so practice the jump out loud. Natively, a desktop app for Mac and Windows, can read the scoring rules from a screenshot in a mock session, nudge you from the stack toward the depth observation, and keep a transcript of how you explained it, so you can see whether you justified the 2^depth step or just asserted it. Read more about practicing problems with Natively.

Questions people ask

How do you solve Score of Parentheses?

Keep a stack starting with 0. Push 0 on every opening bracket. On a closing bracket, pop the inner score v and add max(2v, 1) to the new top. The remaining value is the answer.

Can Score of Parentheses be solved in O(1) space?

Yes. Only empty pairs create value, and each enclosing pair doubles it, so add 2 to the power of the depth for every closing bracket that directly follows an opening one.

What is the time complexity of Score of Parentheses?

O(n) for both the stack and the depth method. The direct recursive split can be O(n squared) on deeply nested input.

Why is the score of "()" 1 and not 2?

By the rules an empty pair is worth 1. Doubling applies only when a pair wraps a non-empty balanced string, which is why the stack uses max(2v, 1).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP