Print Bracket Number - GeeksforGeeks

21 May, 2021
Given an expression exp of length n consisting of some brackets. The task is to print the bracket numbers when the expression is being parsed.Examples :  
Input : (a+(b*c))+(d/e)
Output : 1 2 2 1 3 3
The highlighted brackets in the given expression
(a+(b*c))+(d/e) has been assigned the numbers as:
1 2 2 1 3 3.

Input : ((())(()))
Output : 1 2 3 3 2 4 5 5 4 1 
Source: Flipkart Interview Experience | Set 49.
 
Approach :  
Define a variable left_bnum = 1.Create a stack right_bnum.Now, for i = 0 to n-1.If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
Define a variable left_bnum = 1.
Create a stack right_bnum.
Now, for i = 0 to n-1.If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.
Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to print the bracket number#include <bits/stdc++.h> using namespace std; // function to print the bracket numbervoid printBracketNumber(string exp, int n){    // used to print the bracket number    // for the left bracket    int left_bnum = 1;         // used to obtain the bracket number    // for the right bracket    stack<int> right_bnum;         // traverse the given expression 'exp'    for (int i = 0; i < n; i++) {                 // if current character is a left bracket        if (exp[i] == '(') {            // print 'left_bnum',            cout << left_bnum << " ";                         // push 'left_bum' on to the stack 'right_bnum'            right_bnum.push(left_bnum);                         // increment 'left_bnum' by 1            left_bnum++;        }                 // else if current character is a right bracket        else if(exp[i] == ')') {             // print the top element of stack 'right_bnum'            // it will be the right bracket number            cout << right_bnum.top() << " ";                         // pop the top element from the stack            right_bnum.pop();        }    }} // Driver program to test aboveint main(){    string exp = "(a+(b*c))+(d/e)";    int n = exp.size();         printBracketNumber(exp, n);         return 0;}
// Java implementation to// print the bracket numberimport java.io.*;import java.util.*; class GFG{    // function to print    // the bracket number    static void printBracketNumber(String exp,                                   int n)    {        // used to print the        // bracket number for        // the left bracket        int left_bnum = 1;                 // used to obtain the        // bracket number for        // the right bracket        Stack<Integer> right_bnum =                   new Stack<Integer>();                 // traverse the given        // expression 'exp'        for (int i = 0; i < n; i++)        {                         // if current character            // is a left bracket            if (exp.charAt(i) == '(')            {                                 // print 'left_bnum',                System.out.print(                       left_bnum + " ");                                 // push 'left_bum' on to                // the stack 'right_bnum'                right_bnum.push(left_bnum);                                 // increment 'left_bnum' by 1                left_bnum++;            }                         // else if current character            // is a right bracket            else if(exp.charAt(i) == ')')            {                     // print the top element                // of stack 'right_bnum'                // it will be the right                // bracket number                System.out.print(                       right_bnum.peek() + " ");                                 // pop the top element                // from the stack                right_bnum.pop();            }        }    }         // Driver Code    public static void main(String args[])    {        String exp = "(a+(b*c))+(d/e)";        int n = exp.length();                 printBracketNumber(exp, n);    }} // This code is contributed// by Manish Shaw(manishshaw1)
# Python3 implementation to print the bracket number # function to print the bracket numberdef printBracketNumber(exp, n):     # used to print the bracket number    # for the left bracket    left_bnum = 1     # used to obtain the bracket number    # for the right bracket    right_bnum = list()     # traverse the given expression 'exp'    for i in range(n):         # if current character is a left bracket        if exp[i] == '(':             # print 'left_bnum',            print(left_bnum, end = " ")             # push 'left_bum' on to the stack 'right_bnum'            right_bnum.append(left_bnum)             # increment 'left_bnum' by 1            left_bnum += 1         # else if current character is a right bracket        elif exp[i] == ')':             # print the top element of stack 'right_bnum'            # it will be the right bracket number            print(right_bnum[-1], end = " ")             # pop the top element from the stack            right_bnum.pop() # Driver Codeif __name__ == "__main__":    exp = "(a+(b*c))+(d/e)"    n = len(exp)     printBracketNumber(exp, n) # This code is contributed by# sanjeev2552
// C# implementation to// print the bracket numberusing System;using System.Collections.Generic; class GFG{    // function to print    // the bracket number    static void printBracketNumber(string exp,                                   int n)    {        // used to print the bracket        // number for the left bracket        int left_bnum = 1;                 // used to obtain the bracket         // number for the right bracket        Stack<int> right_bnum = new Stack<int>();                 // traverse the given        // expression 'exp'        for (int i = 0; i < n; i++)        {                         // if current character            // is a left bracket            if (exp[i] == '(')            {                                 // print 'left_bnum',                Console.Write(left_bnum + " ");                                 // Push 'left_bum' on to                // the stack 'right_bnum'                right_bnum.Push(left_bnum);                                 // increment 'left_bnum' by 1                left_bnum++;            }                         // else if current character            // is a right bracket            else if(exp[i] == ')')            {                     // print the top element                // of stack 'right_bnum'                // it will be the right                // bracket number                Console.Write(right_bnum.Peek() + " ");                                 // Pop the top element                // from the stack                right_bnum.Pop();            }        }    }         // Driver Code    static void Main()    {        string exp = "(a+(b*c))+(d/e)";        int n = exp.Length;                 printBracketNumber(exp, n);    }} // This code is contributed// by Manish Shaw(manishshaw1)
<?php// PHP implementation to// print the bracket number // function to print// the bracket numberfunction printBracketNumber($exp, $n){    // used to print the    // bracket number for    // the left bracket    $left_bnum = 1;         // used to obtain the    // bracket number for    // the right bracket    $right_bnum = array();    $t = 0;         // traverse the given    // expression 'exp'    for ($i = 0; $i < $n; $i++)    {                 // if current character        // is a left bracket        if ($exp[$i] == '(')        {                         // print 'left_bnum',            echo $left_bnum . " ";                         // push 'left_bum' on to            // the stack 'right_bnum'            $right_bnum[$t++] = $left_bnum;                         // increment 'left_bnum' by 1            $left_bnum++;        }                 // else if current character        // is a right bracket        else if($exp[$i] == ')')        {             // print the top element            // of stack 'right_bnum'            // it will be the right            // bracket number            echo $right_bnum[$t - 1] . " ";                         // pop the top element            // from the stack            $right_bnum[$t - 1] = 1;            $t--;        }    }} // Driver Code$exp = "(a+(b*c))+(d/e)";$n = strlen($exp); printBracketNumber($exp, $n);     // This code is contributed// by mits?>
<script> // Javascript implementation to print the bracket number // function to print the bracket numberfunction printBracketNumber(exp, n){    // used to print the bracket number    // for the left bracket    var left_bnum = 1;         // used to obtain the bracket number    // for the right bracket    var right_bnum = [];         // traverse the given expression 'exp'    for (var i = 0; i < n; i++) {                 // if current character is a left bracket        if (exp[i] == '(') {            // print 'left_bnum',            document.write( left_bnum + " ");                         // push 'left_bum' on to the stack 'right_bnum'            right_bnum.push(left_bnum);                         // increment 'left_bnum' by 1            left_bnum++;        }                 // else if current character is a right bracket        else if(exp[i] == ')') {             // print the top element of stack 'right_bnum'            // it will be the right bracket number            document.write( right_bnum[right_bnum.length-1] + " ");                         // pop the top element from the stack            right_bnum.pop();        }    }} // Driver program to test abovevar exp = "(a+(b*c))+(d/e)";var n = exp.length; printBracketNumber(exp, n); </script>
1 2 2 1 3 3
 
Time Complexity : O(n). Auxiliary Space : O(n).  
YouTubeGeeksforGeeks500K subscribersPrint Bracket Number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hOO5pvZeH4s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
manishshaw1
Mithun Kumar
sanjeev2552
rrrtnx
expression-evaluation
Flipkart
Mathematical
Stack
Strings
Flipkart
Strings
Mathematical
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Operators in C / C++
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Program for Tower of Hanoi
Inorder Tree Traversal without Recursion