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.
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
- 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.
1 2 2 1 3 3
Time Complexity : O(n).
Auxiliary Space : O(n).
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.
- Find index of closing bracket for a given opening bracket in an expression
- Check if the bracket sequence can be balanced with at most one change in the position of a bracket
- Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2
- Print all ways to break a string in bracket form
- Print the balanced bracket expression using given brackets
- Minimum number of bracket reversals needed to make an expression balanced
- Number of closing brackets needed to complete a regular bracket sequence
- Number of balanced bracket subsequence of length 2 and 4
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum Swaps for Bracket Balancing
- Construct Binary Tree from String with bracket representation
- Expression contains redundant bracket or not
- Range Queries for Longest Correct Bracket Subsequence
- Range Queries for Longest Correct Bracket Subsequence Set | 2
- Convert an unbalanced bracket sequence to a balanced sequence
- Check if expression contains redundant bracket or not | Set 2
- Minimum Cost required to generate a balanced Bracket Sequence
- Count distinct regular bracket sequences which are not N periodic
- Print shortest path to print a string on screen
- Print a number strictly less than a given number such that all its digits are distinct.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.