VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-bracket-number/

⇱ Print Bracket Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

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.


Output
1 2 2 1 3 3 

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

Comment