Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Score of Parentheses

Moderate
0/80
Average time to solve is 15m
profile
Contributed by
7 upvotes
Asked in companies
LinkedInWalmart

Problem statement

One day Ninja goes to play some intellectual games. There was a game where Ninja is given a string of balanced parentheses 'STR' and he has to calculate the score of that using the given rules of the game. If he wins that game, the amount which he has paid for that game will be refunded.

Rules for the game are as follows:

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

Your task is to find the score using these rules for the given string 'STR'.

Example :

Suppose given string 'STR' is “( ( ) )”.
So we return ‘2’ as input is of the form “(x)”, therefore total score = 2 * score of “()” = 2 * 1 = 2.
Note :
You are not required to print anything explicitly. It has already been taken care of. Just implement the function.
Detailed explanation ( Input/output format, Notes, Images )

Sample Input 1 :

2
4
()()
6
(()())

Sample Output 1 :

2
4

Explanation of Sample Input 1 :

Test Case 1 :

For the first test case, the given string 'STR' is “( ) ( )”. As 'STR' is in the form 'x + y', so we return ‘2’ as the score we get is 1 + 1 = 2.


Test Case 2 :

For this test case, the given string 'STR' is “( ( ) ( ) )”. So we return ‘4’ as the score we get is 2 * ( 1 + 1 ) = 4 as it is in the form '(x + y)'.

Sample Input 2 :

2
2
()
8
(()(()))

Sample Output 2 :

1
6

Explanation of Sample Input 2 :

Test Case 1 :

For the first test case, the given string 'STR' is “( )”. So we return ‘1’ as only one balanced parenthesis is present.


Test Case 2 :

For this test case, the given string 'STR' is “( ( ) ( ( ) ) )”. As 'STR' is in the form '( x + ( y ) )', so we return ‘6’ as the score we get is 2 * ( 1 + 2 * (1) ) = 6.
Full screen
Console