Score of Parentheses - Problem

Given a balanced parentheses string s, calculate its score based on a simple scoring system that rewards proper nesting.

The Scoring Rules:

  • () has a score of 1
  • Concatenated strings AB have score A + B, where A and B are balanced parentheses strings
  • Nested strings (A) have score 2 * A, where A is a balanced parentheses string

For example, "()()" scores 2 (1 + 1), while "(())" scores 2 (2 * 1). The deeper the nesting, the higher the exponential growth!

Your task: Return the total score of the given balanced parentheses string.

Input & Output

example_1.py โ€” Basic nesting
$ Input: "(())"
โ€บ Output: 2
๐Ÿ’ก Note: The inner () scores 1 point. The outer parentheses double this score: 2 ร— 1 = 2.
example_2.py โ€” Adjacent pairs
$ Input: "()()"
โ€บ Output: 2
๐Ÿ’ก Note: Two adjacent () pairs, each scoring 1 point. Total: 1 + 1 = 2.
example_3.py โ€” Complex nesting
$ Input: "(()())"
โ€บ Output: 4
๐Ÿ’ก Note: Inside the outer parentheses: () scores 1, () scores 1, so inner total is 1 + 1 = 2. The outer parentheses double this: 2 ร— 2 = 4.

Constraints

  • 1 โ‰ค s.length โ‰ค 50
  • s consists of only '(' and ')' characters
  • s is a balanced parentheses string

Visualization

Tap to expand
๐Ÿช† Parentheses as Russian Nesting Dolls"(())" = Score 21Inner doll: 1 pointOuter layer: 2 ร— 1 = 2"()()" = Score 211Two separate dollsTotal: 1 + 1 = 2"((()))" = Score 41Innermost: 1 pointMiddle layer: 2 ร— 1 = 2Outer layer: 2 ร— 2 = 4
Understanding the Visualization
1
Identify the dolls
Each () pair represents a complete doll. Nested pairs represent dolls inside other dolls
2
Score innermost dolls
The smallest dolls () are worth 1 point each
3
Apply nesting multiplier
Each layer that wraps around doubles the inner value
4
Add adjacent values
Dolls sitting side by side contribute their values independently
Key Takeaway
๐ŸŽฏ Key Insight: Use a stack to track nesting levels and apply scoring rules in real-time, avoiding the need for complex recursive parsing!
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 22
58.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen