VOOZH about

URL: https://www.geeksforgeeks.org/dsa/calculate-score-of-parentheses-from-a-given-string/

โ‡ฑ Score of Balanced Parentheses - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Score of Balanced Parentheses

Last Updated : 15 Sep, 2025

Given a string s, consisting of pairs of balanced parentheses, find the score of the given string based on the given rules:

  • โ€œ()โ€ has a score of 1.
  • โ€œA Bโ€ has a score of A + B, where A and B are individual pairs of balanced parentheses.
  • โ€œ(A)โ€ has a score twice of A i.e., the score is 2 * score of A.

Examples:

Input: s = โ€œ()()โ€ 
Output:
Explanation: The string s is of the form "AB", that makes the total score = (score of A) + (score of B) = 1 + 1 = 2.

Input: s = "(()(()))"
Output: 6
Explanation: The string s is of the form "(A(B))" which makes the total score = 2 ร— ((score of A) + 2 ร— (score of B)) = 2 ร— (1 + 2 ร— (1)) = 6.

[Approach] Using Stack - O(n) Time and O(n) Space

Think of the string as a tree-like structure:

  • Every '(' means we are going down to a child level.
  • Every ')' means we are returning back to the parent level.

To keep track of scores at each level, we use a stack.

Now, how does the stack help?

The stack keeps track of the score at each level. When we go down '(', we push 0 to start for that level. When we come back through ')', we pop the score of that level:

  • If it was empty "()", score = 1.
  • If it had children "(A)", score = 2 ร— innerScore.

Then we add this score to the parentโ€™s score (the new top of the stack). At the end, only the root score is left in the stack and thatโ€™s our total score.



Output
6
Comment