Compute the score of a balanced parentheses string

Quick Overview

Compute the score of a balanced parentheses string where "()" is worth 1, side-by-side parts add, and wrapping a part in a pair of parentheses doubles it. It tests stack-based parsing of nested structure and careful handling of the scoring rules.

Compute the score of a balanced parentheses string

Company: ByteDance

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given a balanced parentheses string `s`, return the score of the string. The score of a balanced parentheses string is based on the following rule: - `"()"` has score `1`. - `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. - `(A)` has score `2 * A`, where `A` is a balanced parentheses string. Here `A + B` and `2 * A` stand for the scores of `A` and `B`, so `"(())"` scores `2 * 1 = 2`. ### Function Signature ```python def score_of_parentheses(s: str) -> int: ``` ### Constraints - `2 <= s.length <= 50` - `s` consists of only `'('` and `')'`. - `s` is a balanced parentheses string. ### Examples ```text Input: s = "()" Output: 1 ``` A single `"()"` scores 1. ```text Input: s = "(()(()))" Output: 6 ``` The inside of the outer pair is `"()(())"`, which scores `1 + 2 * 1 = 3`. Wrapping it in the outer pair doubles that to 6. ```text Input: s = "()(()())" Output: 5 ``` The string is `"()"` followed by `"(()())"`. The first part scores 1. The second part wraps `"()()"`, which scores 2, so it scores 4. The total is 5.

Overview: Compute the score of a balanced parentheses string where "()" is worth 1, side-by-side parts add, and wrapping a part in a pair of parentheses doubles it. It tests stack-based parsing of nested structure and careful handling of the scoring rules.

ByteDance logo
ByteDance
Nov 25, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given a balanced parentheses string s, return the score of the string.

The score of a balanced parentheses string is based on the following rule:

  • "()" has score 1 .
  • AB has score A + B , where A and B are balanced parentheses strings.
  • (A) has score 2 * A , where A is a balanced parentheses string.

Here A + B and 2 * A stand for the scores of A and B, so "(())" scores 2 * 1 = 2.

Function Signature

def score_of_parentheses(s: str) -> int:

Constraints

  • 2 <= s.length <= 50
  • s consists of only '(' and ')' .
  • s is a balanced parentheses string.

Examples

Input: s = "()"
Output: 1

A single "()" scores 1.

Input: s = "(()(()))"
Output: 6

The inside of the outer pair is "()(())", which scores 1 + 2 * 1 = 3. Wrapping it in the outer pair doubles that to 6.

Input: s = "()(()())"
Output: 5

The string is "()" followed by "(()())". The first part scores 1. The second part wraps "()()", which scores 2, so it scores 4. The total is 5.