Design Gurus Logo
Score of Parentheses (medium)

Problem Statement

Given a balanced parenthesis string s, return the score of the given string.

Follow the below rules to determine the score of the string s.

  • "()" has score 1.
  • XY has score X + Y, where X and Y both are balanced parentheses strings.
  • (X) has score 2 * X, where X is a balanced parentheses string.

Examples

Example 1:

  • Input: "((()))"
  • Expected Output: 4
  • Justification: The string represents a pair of parentheses inside another pair, which is again inside another pair. This structure results in a score of ((())) = ((1*2)*2) = 4.

Example 2:

  • Input: "(()())"
  • Expected Output: 4
  • Justification: Here, we have a pair of parentheses inside another pair (()()) and another pair next to it. The total score is (1*2) + (1*2) = 4.

Example 3:

  • Input: "(()(()))"
  • Expected Output: 6
  • Justification: The innermost () scores 1, its surrounding () doubles it to 2, the previous () adjacent to the inner pair scores 1 and is then doubled by its surrounding pair, resulting in 2 + (1*2)*2 = 6.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory