# Calculate score of a string consisting of balanced parentheses

• Difficulty Level : Medium
• Last Updated : 10 Jun, 2021

Given a string str consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the following rules:

1. ()” has a score of 1.
2. x y” has a score of x + y where x and y are individual pairs of balanced parentheses.
3. (x)” has a score twice of x (i.e), 2 * score of x.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str = “()()”
Output: 2
Explanation: There are are two individual psirs of balanced parenthesis “() ()”. Therefore, score = score of “()” + score of “()” = 1 + 1 = 2

Input: str = “(())”
Output: 2
Explanation: Since the input is of the form “(x)”, the total score = 2 * score of “()” = 2 * 1 = 2

Approach: The problem can be solved using Stack. The idea is to iterate over the characters of the string. For every ith character check if the character is ‘(‘ or not. If found to be true, then insert the character into the stack. Otherwise, calculate the score of the inner parenthesis and insert double of the score into the stack. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach``#include ``#include ``using` `namespace` `std;` `// Function to calculate``// score of parentheses``long` `long` `scoreOfParentheses(string S)``{` `    ``stack s;` `    ``// Stores index of``    ``// character of string``    ``int` `i = 0;` `    ``// Stores total scores``    ``// obtained from the string``    ``long` `long` `ans = 0;` `    ``// Iterate over characters``    ``// of the string``    ``while` `(i < S.length()) {` `        ``// If s[i] is '('``        ``if` `(S[i] == ``'('``)``            ``s.push(``"("``);``        ``else` `{` `            ``// If top element of``            ``// stack is '('``            ``if` `(s.top() == ``"("``) {``                ``s.pop();``                ``s.push(``"1"``);``            ``}``            ``else` `{` `                ``// Stores score of``                ``// inner parentheses``                ``long` `long` `count = 0;` `                ``// Calculate score of``                ``// inner parentheses``                ``while` `(s.top() != ``"("``) {` `                    ``// Update count``                    ``count += stoi(s.top());``                    ``s.pop();``                ``}` `                ``// Pop from stack``                ``s.pop();` `                ``// Insert score of``                ``// inner parentheses``                ``s.push(to_string(2 * count));``            ``}``        ``}` `        ``// Update i``        ``i++;``    ``}` `    ``// Calculate score``    ``// of the string``    ``while` `(!s.empty()) {` `        ``// Update ans``        ``ans += stoi(s.top());``        ``s.pop();``    ``}``    ``return` `ans;``}` `// Driver Code``int` `main()``{``    ``string S1 = ``"(()(()))"``;``    ``cout << scoreOfParentheses(S1) << endl;` `    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;``class` `GFG``{` `  ``// Function to calculate``  ``// score of parentheses``  ``static` `long` `scoreOfParentheses(String S)``  ``{``    ``Stack s = ``new` `Stack<>();` `    ``// Stores index of``    ``// character of String``    ``int` `i = ``0``;` `    ``// Stores total scores``    ``// obtained from the String``    ``long` `ans = ``0``;` `    ``// Iterate over characters``    ``// of the String``    ``while` `(i < S.length())``    ``{` `      ``// If s[i] is '('``      ``if` `(S.charAt(i) == ``'('``)``        ``s.add(``"("``);``      ``else``      ``{` `        ``// If top element of``        ``// stack is '('``        ``if` `(s.peek() == ``"("``)``        ``{``          ``s.pop();``          ``s.add(``"1"``);``        ``}``        ``else``        ``{` `          ``// Stores score of``          ``// inner parentheses``          ``long` `count = ``0``;` `          ``// Calculate score of``          ``// inner parentheses``          ``while` `(s.peek() != ``"("``)``          ``{` `            ``// Update count``            ``count += Integer.parseInt(s.peek());``            ``s.pop();``          ``}` `          ``// Pop from stack``          ``s.pop();` `          ``// Insert score of``          ``// inner parentheses``          ``s.add(String.valueOf(``2` `* count));``        ``}``      ``}` `      ``// Update i``      ``i++;``    ``}` `    ``// Calculate score``    ``// of the String``    ``while` `(!s.isEmpty())``    ``{` `      ``// Update ans``      ``ans += Integer.parseInt(s.peek());``      ``s.pop();``    ``}``    ``return` `ans;``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``String S1 = ``"(()(()))"``;``    ``System.out.print(scoreOfParentheses(S1) +``"\n"``);``  ``}``}` `// This code is contributed by 29AjayKumar.`

## Python3

 `# Python3 program to implement``# the above approach` `# Function to calculate``# score of parentheses``def` `scoreOfParentheses(S):``    ``s ``=` `[]` `    ``# Stores index of``    ``# character of string``    ``i ``=` `0` `    ``# Stores total scores``    ``# obtained from the string``    ``ans ``=` `0` `    ``# Iterate over characters``    ``# of the string``    ``while` `(i < ``len``(S)):` `        ``# If s[i] is '('``        ``if` `(S[i] ``=``=` `'('``):``            ``s.append(``"("``)``        ``else``:` `            ``# If top element of``            ``# stack is '('``            ``if` `(s[``-``1``] ``=``=` `"("``):``                ``s.pop()``                ``s.append(``"1"``)``            ``else``:` `                ``# Stores score of``                ``# inner parentheses``                ``count ``=` `0` `                ``# Calculate score of``                ``# inner parentheses``                ``while` `(s[``-``1``] !``=` `"("``):` `                    ``# Update count``                    ``count ``+``=` `int``(s[``-``1``])``                    ``s.pop()` `                ``# Pop from stack``                ``s.pop()` `                ``# Insert score of``                ``# inner parentheses``                ``s.append(``str``(``2` `*` `count))` `        ``# Update i``        ``i ``+``=` `1` `    ``# Calculate score``    ``# of the string``    ``while` `len``(s) > ``0``:` `        ``# Update ans``        ``ans ``+``=` `int``(s[``-``1``])``        ``s.pop()``    ``return` `ans``  ` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``S1 ``=` `"(()(()))"``    ``print``(scoreOfParentheses(S1))` `    ``# This code is contributed by mohit kumar 29`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG``{` `  ``// Function to calculate``  ``// score of parentheses``  ``static` `long` `scoreOfParentheses(String S)``  ``{``    ``Stack s = ``new` `Stack();` `    ``// Stores index of``    ``// character of String``    ``int` `i = 0;` `    ``// Stores total scores``    ``// obtained from the String``    ``long` `ans = 0;` `    ``// Iterate over characters``    ``// of the String``    ``while` `(i < S.Length)``    ``{` `      ``// If s[i] is '('``      ``if` `(S[i] == ``'('``)``        ``s.Push(``"("``);``      ``else``      ``{` `        ``// If top element of``        ``// stack is '('``        ``if` `(s.Peek() == ``"("``)``        ``{``          ``s.Pop();``          ``s.Push(``"1"``);``        ``}``        ``else``        ``{` `          ``// Stores score of``          ``// inner parentheses``          ``long` `count = 0;` `          ``// Calculate score of``          ``// inner parentheses``          ``while` `(s.Peek() != ``"("``)``          ``{` `            ``// Update count``            ``count += Int32.Parse(s.Peek());``            ``s.Pop();``          ``}` `          ``// Pop from stack``          ``s.Pop();` `          ``// Insert score of``          ``// inner parentheses``          ``s.Push(String.Join(``""``, 2 * count));``        ``}``      ``}` `      ``// Update i``      ``i++;``    ``}` `    ``// Calculate score``    ``// of the String``    ``while` `(s.Count != 0)``    ``{` `      ``// Update ans``      ``ans += Int32.Parse(s.Peek());``      ``s.Pop();``    ``}``    ``return` `ans;``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(String[] args)``  ``{``    ``String S1 = ``"(()(()))"``;``    ``Console.Write(scoreOfParentheses(S1) +``"\n"``);``  ``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``
Output:
`6`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up