Score of Parentheses - Problem

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

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

  • () 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

Input & Output

Example 1 — Basic Nested
$ Input: s = "(())"
Output: 2
💡 Note: Inner () has score 1, outer parentheses double it: 2 * 1 = 2
Example 2 — Complex Structure
$ Input: s = "(()(()))"
Output: 6
💡 Note: First () at depth 1 contributes 2¹ = 2, second () at depth 2 contributes 2² = 4, total: 2 + 4 = 6
Example 3 — Simple Concatenation
$ Input: s = "()()"
Output: 2
💡 Note: Two separate () pairs: 1 + 1 = 2

Constraints

  • 2 ≤ s.length ≤ 50
  • s consists of only '(' and ')'

Visualization

Tap to expand
Score of Parentheses INPUT String s = "(())" ( i=0 ( i=1 ) i=2 ) i=3 Depth Tracking depth=0: outer level depth=1: first ( depth=2: nested ( Scoring Rules () = 1 point AB = A + B (A) = 2 * A ALGORITHM STEPS 1 Initialize depth=0, score=0 2 Process '(' Increment depth++ 3 Process ')' If prev='(' add 2^(depth-1) Decrement depth-- 4 Return Score Final accumulated score Execution Trace '(' : depth=1 '(' : depth=2 ')' : prev='(' score+=2^1=2 depth=1 ')' : depth=0 FINAL RESULT Structure Breakdown ( ... ) ( ) score = 1 Outer ( ) doubles inner Calculation (()) = 2 * () = 2 * 1 = 2 OUTPUT 2 OK - Score computed! Key Insight: The depth counting approach works because each '()' pair at depth d contributes 2^(d-1) to the score. We only add score when we see ')' immediately after '(' (a complete pair). Nesting is handled by depth. Time: O(n), Space: O(1) - optimal solution without using a stack! TutorialsPoint - Score of Parentheses | Depth Counting (Optimal)
Asked in
Google 42 Microsoft 35
89.2K Views
Medium Frequency
~15 min Avg. Time
2.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