Print Bracket Number

Given a string str, the task is to find the bracket numbers, i.e., for each bracket in str, return i if the bracket is the ith opening or closing bracket to appear in the string. 

 Examples:

Input:  str = "(aa(bdc))p(dee)"
Output: 1 2 2 1 3 3
Explanation: The highlighted brackets in
the given string (aa(bdc))p(dee) are
assigned the numbers as: 1 2 2 1 3 3.
Input:  str = "(((()("
Output: 1 2 3 4 4 5
Explanation: The highlighted brackets in
the given string (((()( are assigned
the numbers as: 1 2 3 4 4 5

Expected Time Complexity: O(|str|)
Expected Auxiliary Space: O(|str|)

Constraints:
1 <= |str| <= 105
str contains lowercase English alphabets, and ‘(‘, ‘)’ characters
At any index, the number of opening brackets is greater than or equal to closing brackets.


Approach 01

#include <iostream>
#include <string>
#include <vector>
#include <stack>

using namespace std;

class Solution {
  public:
    vector<int> bracketNumbers(string str) {
        vector<int> result;
        stack<int> bracket_stack;
        int bracket_count = 0;
        
        for(int i = 0; i < str.length(); i++) {
            if(str[i] == '(') {
                bracket_count++;
                bracket_stack.push(bracket_count);
                result.push_back(bracket_count);
            }
            if(str[i] == ')') {
                result.push_back(bracket_stack.top());
                bracket_stack.pop();
            }
        }
        return result;
    }
};
from typing import List

class Solution:
    def bracketNumbers(self, str):
        result = []
        bracket_stack = []
        bracket_count = 0

        for char in str:
            if char == '(':
                bracket_count += 1
                bracket_stack.append(bracket_count)
                result.append(bracket_count)
            if char == ')':
                result.append(bracket_stack[-1])
                bracket_stack.pop()

        return result

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top