Given a string with brackets. If the start index of the open bracket is given, find the index of the closing bracket.
Input : string = [ABC] index = 0 Output : 8 The opening bracket at index 0 corresponds to closing bracket at index 8.
The idea is to use Stack data structure. We traverse given expression from given index and keep pushing starting brackets. Whenever we encounter a closing bracket, we pop a starting bracket. If stack becomes empty at any moment, we return that index.
[ABC], 0: 8 [ABC], 4: 7 [ABC], 9: 12 [ABC], 1: -1
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.
- Number of closing brackets needed to complete a regular bracket sequence
- 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
- Minimum number of bracket reversals needed to make an expression balanced
- Expression contains redundant bracket or not
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Check if expression contains redundant bracket or not | Set 2
- Find all the patterns of "1(0+)1" in a given string | SET 2(Regular Expression Approach)
- Find the missing digit x from the given expression
- Print all ways to break a string in bracket form
- Construct Binary Tree from String with bracket representation
- Print Bracket Number
- Range Queries for Longest Correct Bracket Subsequence
- Range Queries for Longest Correct Bracket Subsequence Set | 2
- Number of balanced bracket subsequence of length 2 and 4
- Convert an unbalanced bracket sequence to a balanced sequence
- Minimum Cost required to generate a balanced Bracket Sequence
- Count distinct regular bracket sequences which are not N periodic
- Minimum Swaps for Bracket Balancing
- Find if an expression has duplicate parenthesis or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.