Score of Parentheses

Medium

Topics
StringStack

Given a balanced parentheses string s, compute its score: () is 1, AB is A+B, and (A) is 2*A.

Example 1

(0)1
Two rules, and the nesting is what makes them need a stack: () 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.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "()"
Output: 1

Example 2

(0(1)2)3
Input:  s = "(())"
Output: 2

Example 3

(0)1(2)3
Input:  s = "()()"
Output: 2

Example 4

(0(1)2(3(4)5)6)7
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

  1. Start with a stack holding one zero, the score at the outermost level.
  2. On (, push 0.
  3. On ), pop v and add max(2v, 1) to the new top.
  4. 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      "()()" -> 2

Complexity

  • 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 * v without the max, which scores every bare () as 0 and collapses the whole answer to zero.
  • Writing max(2 * v, 1) as 2 * v + 1. The 1 is 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]
SensAI
Beta
Tap the mic to stop voice mode