Score of Parentheses using Tree
Last Updated :
29 Dec, 2022
Given a string str which contains pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules:
- “()” has a score of 1.
- “x y” has a score of x + y where x and y are individual pairs of balanced parentheses.
- “(x)” has a score twice of x (i.e), the score is 2 * score of x.
Examples:
Input: str = “()()”
Output: 2
Explanation:
Here input is of the form “xy” which makes the total score = score of x + score of y
and hence, score = 1 + 1 = 2
Input: str = “(())”
Output: 2
Explanation:
Here input is of the form “(x)” which makes the total score = 2 * score of x
and hence, score = 2 * 1 = 2
Input: str = “(()()())”
Output: 6
Explanation:
Here input is of the form “(xyz)” which makes the total score = 2 * (score of x +
score of y + score of z) and hence 2*(1 + 1 + 1) = 6
Approach: The idea is to use a tree data structure to solve this problem along with Recursion.
- The root node of our tree structure will represent the outermost pair of our input parentheses.
- For every pair of balanced parentheses included inside the outermost parentheses, we will add a child to our root node.
- This process of declaring a child to a root node will be recursive and hence it will create a node in our tree structure for every pair of balanced parentheses in a hierarchy.
- Every balanced pair of parentheses will be considered as outermost (recursively) and generate a node and hence will allow us to calculate the score.
- When computing score, each leaf node of our tree will be considered with a score of 1 and to get the score of its respective root node we need to add the scores of each child node and double that aggregate.
- The diagram below shows the recursive structure of the tree generated and we start from the bottom to calculate the scores at each level until we reach the outermost ending parentheses.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
class TreeNode {
TreeNode* parent = NULL;
vector<TreeNode*> children;
public :
void addChild(TreeNode* node)
{
children.push_back(node);
}
void setParent(TreeNode* node)
{
parent = node;
}
TreeNode* getParent()
{
return parent;
}
int computeScore()
{
if (children.size() == 0)
return 1;
int res = 0;
for (TreeNode* curr : children)
res += curr->computeScore();
if (parent == NULL)
return res;
else
return 2 * res;
}
};
TreeNode* computeTree(string s)
{
TreeNode* current = new TreeNode();
TreeNode* root = current;
for ( int i = 0; i < s.size(); i++) {
if (s[i] == '(' ) {
TreeNode* child = new TreeNode();
child->setParent(current);
current->addChild(child);
current = child;
}
else {
current = current->getParent();
}
}
return root;
}
int main()
{
string s = "(()(()))" ;
TreeNode* root = computeTree(s);
cout << root->computeScore();
return 0;
}
|
Java
import java.util.*;
public class Main
{
static class TreeNode {
public TreeNode parent = null ;
public Vector<TreeNode> children = new Vector<TreeNode>();
public void addChild(TreeNode node)
{
children.add(node);
}
public void setParent(TreeNode node)
{
parent = node;
}
public TreeNode getParent()
{
return parent;
}
public int computeScore()
{
if (children.size() == 0 )
return 1 ;
int res = 0 ;
for (TreeNode curr : children)
res += curr.computeScore();
if (parent == null )
return res;
else
return 2 * res;
}
}
static TreeNode computeTree(String s)
{
TreeNode current = new TreeNode();
TreeNode root = current;
for ( int i = 0 ; i < s.length(); i++)
{
if (s.charAt(i) == '(' )
{
TreeNode child = new TreeNode();
child.setParent(current);
current.addChild(child);
current = child;
}
else
{
current = current.getParent();
}
}
return root;
}
public static void main(String[] args) {
String s = "(()(()))" ;
TreeNode root = computeTree(s);
System.out.print(root.computeScore());
}
}
|
Python3
class TreeNode:
def __init__( self ):
self .parent = None
self .children = []
def addChild( self , node):
self .children.append(node);
def setParent( self , node):
self .parent = node;
def getParent( self ):
return self .parent;
def computeScore( self ):
if ( len ( self .children) = = 0 ):
return 1 ;
res = 0 ;
for curr in self .children:
res + = curr.computeScore();
if ( self .parent = = None ):
return res;
else :
return 2 * res;
def computeTree(s):
current = TreeNode();
root = current;
for i in range ( len (s)):
if (s[i] = = '(' ):
child = TreeNode();
child.setParent(current);
current.addChild(child);
current = child;
else :
current = current.getParent();
return root;
if __name__ = = '__main__' :
s = "(()(()))" ;
root = computeTree(s);
print (root.computeScore())
|
C#
using System;
using System.Collections;
class GFG{
class TreeNode
{
public TreeNode parent = null ;
public ArrayList children = new ArrayList();
public void addChild(TreeNode node)
{
children.Add(node);
}
public void setParent(TreeNode node)
{
parent = node;
}
public TreeNode getParent()
{
return parent;
}
public int computeScore()
{
if (children.Count == 0)
return 1;
int res = 0;
foreach (TreeNode curr in children)
res += curr.computeScore();
if (parent == null )
return res;
else
return 2 * res;
}
};
static TreeNode computeTree( string s)
{
TreeNode current = new TreeNode();
TreeNode root = current;
for ( int i = 0; i < s.Length; i++)
{
if (s[i] == '(' )
{
TreeNode child = new TreeNode();
child.setParent(current);
current.addChild(child);
current = child;
}
else
{
current = current.getParent();
}
}
return root;
}
public static void Main()
{
string s = "(()(()))" ;
TreeNode root = computeTree(s);
Console.Write(root.computeScore());
}
}
|
Javascript
class TreeNode {
constructor() {
this .parent = null ;
this .children = [];
}
addChild(node) {
this .children.push(node);
}
setParent(node) {
this .parent = node;
}
getParent() {
return this .parent;
}
computeScore() {
if ( this .children.length === 0) return 1;
let res = 0;
for (let curr of this .children) res += curr.computeScore();
if ( this .parent === null ) return res;
else return 2 * res;
}
}
function computeTree(s) {
let current = new TreeNode();
let root = current;
for (let i = 0; i < s.length; i++)
{
if (s[i] === '(' )
{
let child = new TreeNode();
child.setParent(current);
current.addChild(child);
current = child;
}
else {
current = current.getParent();
}
}
return root;
}
let s = '(()(()))' ;
let root = computeTree(s);
console.log(root.computeScore());
|
Time Complexity: O(N), where N is the length of the input string.
Space Complexity: O(N), where N is the length of the input string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...