Print Bracket Number

Last Updated : 25 Apr, 2025

Given a string s containing brackets and characters, the task is to find the bracket numbers for each bracket in the string. A bracket number represents the order in which a specific bracket appears as either an opening or a closing bracket.

Examples: 

Input: "(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.

Try It Yourself
redirect icon

The approach uses a stack to track the opening brackets.

  • For each opening bracket '(', we increment a counter bal, push it onto the stack, and append it to the result list.
  • For each closing bracket ')', we pop the top value from the stack and append it to the result list.

The above two steps ensure that each bracket is assigned the correct number based on its position in the string.

C++
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

vector<int> bracketNumbers(string &str) {
    vector<int> res;
    stack<int> st;
    
    int count = 0;
    for (int i = 0; i < str.size(); i++) {
        if (str[i] == '(') {
            count++;
            res.push_back(count);
            st.push(count);
        }
        else if (str[i] == ')') {
            res.push_back(st.top());
            st.pop();
        }
    }

    return res;
}

int main() {
    string str = "(aa(bdc))p(dee)";
    vector<int> result = bracketNumbers(str);
    
    for (int num : result) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
Java
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static List<Integer> bracketNumbers(String str) {
        List<Integer> res = new ArrayList<>();
        Stack<Integer> st = new Stack<>();
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '(') {
                count++;
                res.add(count);
                st.push(count);
            } else if (str.charAt(i) == ')') {
                res.add(st.pop());
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String str = "(aa(bdc))p(dee)";
        List<Integer> result = bracketNumbers(str);
        for (int num : result) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
def bracket_numbers(s):
    res = []
    st = []
    count = 0
    for char in s:
        if char == '(':  
            count += 1
            res.append(count)
            st.append(count)
        elif char == ')':
            res.append(st.pop())
    return res

if __name__ == '__main__':
    s = '(aa(bdc))p(dee)'
    result = bracket_numbers(s)
    print(' '.join(map(str, result)))
C#
using System;
using System.Collections.Generic;

class Program {
    static List<int> BracketNumbers(string str) {
        List<int> res = new List<int>();
        Stack<int> st = new Stack<int>();
        int count = 0;
        foreach (char c in str) {
            if (c == '(') {
                count++;
                res.Add(count);
                st.Push(count);
            } else if (c == ')') {
                res.Add(st.Pop());
            }
        }
        return res;
    }

    static void Main() {
        string str = "(aa(bdc))p(dee)";
        List<int> result = BracketNumbers(str);
        Console.WriteLine(string.Join(" ", result));
    }
}
JavaScript
function bracketNumbers(str) {
    let res = [];
    let st = [];
    let count = 0;
    for (let char of str) {
        if (char === '(') {
            count++;
            res.push(count);
            st.push(count);
        } else if (char === ')') {
            res.push(st.pop());
        }
    }
    return res;
}

const str = '(aa(bdc))p(dee)';
const result = bracketNumbers(str);
console.log(result.join(' '));

Output
1 2 2 1 3 3 

Time Complexity : O(n)
Auxiliary Space : O(n)

Comment