Open In App

Calculate weight of parenthesis based on the given conditions

Given a valid parenthesis string S, the task is to find the weight of the parenthesis based on the following conditions:  

  1. Weight of “( )” is 1
  2. Weight of “AB” = weight of “A” + weight of “B” (where, A and B are both independent valid parenthesis). e.g. weight of “()()” = weight of “()” + weight of “()”
  3. Weight of “(A)” = 2 times the weight of “A” (where A is an independent valid parenthesis). e.g. weight of “(())” is 2 times the weight of “()”

Examples:  



Input: S = “()(())” 
Output:
Explanation: 
Weight of () = 1 
Weight of (()) = 2 
Hence, the weight of ()(()) = 1 + 2 = 3

Input: S = “(()(()))” 
Output:
Explanation: 
Weight of ()(()) = 3 
Weight of (()(())) = 2 * 3 = 6 
 



Approach: 
This problem can be solved using the Divide and Conquer approach. Follow the steps below to solve the problem: 
 

Below is the implementation of the above approach. 




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// HashMap to store the ending
// index of every opening bracket
unordered_map<int, int> endIndex;
 
// Function to calculate and store
// the closing index of each opening
// bracket in the parenthesis
void getClosingIndex(string s)
{
    int n = s.length();
 
    stack<int> st;
 
    for(int i = 0; i < n; i++)
    {
        if (s[i] == ')')
        {
             
            // If it's a closing bracket,
            // pop index of it's corresponding
            // opening bracket
            int startIndex = st.top();
            st.pop();
             
            // Insert the index of opening
            // bracket and closing bracket
            // as key-value pair in the
            // hashmap
            endIndex[startIndex] = i;
        }
        else
        {
             
            // If it's an opening bracket,
            // push it's index into the stack
            st.push(i);
        }
    }
}
 
// Function to return the weight of
// parenthesis
int calcWeight(string s, int low, int high)
{
     
    // Base case
    if (low + 1 == high)
    {
        return 1;
    }
 
    else
    {
 
        // Mid refers to ending index of
        // opening bracket at index low
        int mid = endIndex[low];
         
        if (mid == high)
        {
            return 2 * calcWeight(s, low + 1,
                                    high - 1);
        }
        else
        {
            return calcWeight(s, low, mid) +
                   calcWeight(s, mid + 1,
                              high);
        }
    }
}
 
// Driver Code
int main()
{
    string input = "(()(()))";
    int n = input.length();
 
    // Update the closing Index
    getClosingIndex(input);
 
    cout << (calcWeight(input, 0, n - 1)) << endl;
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07




// Java Program to implement
// the above approach
import java.util.*;
 
public class GFG {
 
    // HashMap to store the ending
    // index of every opening bracket
    static HashMap<Integer, Integer> endIndex
        = new HashMap<Integer, Integer>();
 
    // Function to calculate and store
    // the closing index of each opening
    // bracket in the parenthesis
    public static void getClosingIndex(String s)
    {
 
        int n = s.length();
 
        Stack<Integer> st = new Stack<Integer>();
 
        for (int i = 0; i < n; i++) {
 
            if (s.charAt(i) == ')') {
 
                // If it's a closing bracket,
                // pop index of it's corresponding
                // opening bracket
                int startIndex = st.pop();
 
                // Insert the index of opening
                // bracket and closing bracket
                // as key-value pair in the
                // hashmap
                endIndex.put(startIndex, i);
            }
            else {
 
                // If it's an opening bracket,
                // push it's index into the stack
                st.push(i);
            }
        }
    }
 
    // Function to return the weight of
    // parenthesis
    public static int calcWeight(String s,
                                int low,
                                int high)
    {
 
        // Base case
        if (low + 1 == high) {
            return 1;
        }
 
        else {
 
            // Mid refers to ending index of
            // opening bracket at index low
            int mid = endIndex.get(low);
            if (mid == high) {
                return 2 * calcWeight(s, low + 1,
                                    high - 1);
            }
            else {
                return calcWeight(s, low, mid)
                    + calcWeight(s, mid + 1,
                                high);
            }
        }
    }
 
    public static void main(String[] args)
    {
        String input = "(()(()))";
        int n = input.length();
 
        // Update the closing Index
        getClosingIndex(input);
 
        System.out.println(calcWeight(input,
                                    0, n - 1));
    }
}




# Python3 program to implement the
# above approach
 
# Function to calculate and store
# the closing index of each opening
# bracket in the parenthesis
def getClosingIndex(string):
 
    # Dictionary to store
    # the ending index of
    # each opening bracket
    endIndex = dict()
 
 
    n = len(string)
 
    stack = []
    for i in range(n):
        if (string[i]==')'):
 
            # If it's a closing bracket,
            # pop index of it's
            # corresponding
            # opening bracket
            startIndex = stack.pop()
 
            # Put the index of opening
            # bracket and closing
            # bracket as key value
            # pair in the Dictionary
            endIndex[startIndex] = i
 
        else:
 
            # If it's an opening bracket,
            # push it's index into
            # the stack
            stack.append(i)
    return endIndex
     
# Function to return the weight
# of parenthesis
def calcWeight(s, low,
                high, endIndex):
 
 
    # Base case
    if (low + 1 == high):
        return 1
    else:
 
        # Mid refers to ending index of
        # opening bracket at index low
        mid = endIndex[low]
        if (mid == high):
            return 2*(calcWeight(s, low + 1,
            high-1, endIndex))
 
        else:
            return calcWeight(s, low,
            mid, endIndex) + calcWeight(s,
            mid + 1, high, endIndex)
 
 
if __name__ == "__main__":
    string = "(()(()))"
    n = len(string)
    endIndex = getClosingIndex(string)
    print(calcWeight(string, 0,
    n-1, endIndex))




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// HashMap to store the ending
// index of every opening bracket
static Dictionary<int,
                  int> endIndex = new Dictionary<int,
                                                 int>();
 
// Function to calculate and store
// the closing index of each opening
// bracket in the parenthesis
public static void getClosingIndex(string s)
{
    int n = s.Length;
 
    Stack<int> st = new Stack<int>();
 
    for(int i = 0; i < n; i++)
    {
        if (s[i] == ')')
        {
             
            // If it's a closing bracket,
            // pop index of it's corresponding
            // opening bracket
            int startIndex = st.Pop();
 
            // Insert the index of opening
            // bracket and closing bracket
            // as key-value pair in the
            // hashmap
            endIndex.Add(startIndex, i);
        }
        else
        {
 
            // If it's an opening bracket,
            // push it's index into the stack
            st.Push(i);
        }
    }
}
 
// Function to return the weight of
// parenthesis
public static int calcWeight(string s, int low,
                                       int high)
{
 
    // Base case
    if (low + 1 == high)
    {
        return 1;
    }
    else
    {
         
        // Mid refers to ending index of
        // opening bracket at index low
        int mid = endIndex[low];
        if (mid == high)
        {
            return 2 * calcWeight(s, low + 1,
                                    high - 1);
        }
        else
        {
            return calcWeight(s, low, mid) +
                   calcWeight(s, mid + 1, high);
        }
    }
}
 
// Driver code
public static void Main(string[] args)
{
    string input = "(()(()))";
    int n = input.Length;
 
    // Update the closing Index
    getClosingIndex(input);
 
    Console.Write(calcWeight(input, 0, n - 1));
}
}
 
// This code is contributed by rutvik_56




<script>
 
// Javascript program to implement
// the above approach
 
// HashMap to store the ending
// index of every opening bracket
var endIndex = new Map();
 
// Function to calculate and store
// the closing index of each opening
// bracket in the parenthesis
function getClosingIndex(s)
{
    var n = s.length;
 
    var st = [];
 
    for(var i = 0; i < n; i++)
    {
        if (s[i] == ')')
        {
             
            // If it's a closing bracket,
            // pop index of it's corresponding
            // opening bracket
            var startIndex = st[st.length-1];
            st.pop();
             
            // Insert the index of opening
            // bracket and closing bracket
            // as key-value pair in the
            // hashmap
            endIndex[startIndex] = i;
        }
        else
        {
             
            // If it's an opening bracket,
            // push it's index into the stack
            st.push(i);
        }
    }
}
 
// Function to return the weight of
// parenthesis
function calcWeight(s, low, high)
{
     
    // Base case
    if (low + 1 == high)
    {
        return 1;
    }
 
    else
    {
 
        // Mid refers to ending index of
        // opening bracket at index low
        var mid = endIndex[low];
         
        if (mid == high)
        {
            return 2 * calcWeight(s, low + 1,
                                    high - 1);
        }
        else
        {
            return calcWeight(s, low, mid) +
                   calcWeight(s, mid + 1,
                              high);
        }
    }
}
 
// Driver Code
var input = "(()(()))";
var n = input.length;
// Update the closing Index
getClosingIndex(input);
document.write((calcWeight(input, 0, n - 1)));
 
 
</script>

Output: 
6

 

Time Complexity: O(N) 
Auxiliary Space: O(N), where N is the length of the string.
 


Article Tags :