Count the letter A at each depth of nested brackets

Updated

Given a string s containing ‘A’, ‘(‘ and ‘)’. The string has balanced brackets and in between there are some ‘A’s along with possibly nested brackets recursively. Find the number of ‘A’s at each depth of brackets in s, from the shallowest to the deepest depth.

Example :

Input : s = "(AA(AA(A))A)"
Output : [3, 2, 1]
Explanation :
There are three 'A's at depth 0 ->"(AA(AA(A))A)"
two 'A's at depth 1 -> "(AA(AA(A))A)"
and one 'A' at depth 2 ->"(AA(AA(A))A)"

Input : s = "(())"
Output : [0, 0]
Explanation :
There's no 'A's but depth goes to 1.

Approach :

We maintain a running depth ‘d’ while looping through the string and at each character there are three cases :

  1. If we encounter ‘(‘ character then depth increases.
  2. If we encounter ‘)’ character then depth decreases.
  3. If we encounter ‘A’ character then this character correspond to the depth ‘d’ and we increase the value in hash map by 1.
  4. Finally we return the answer by storing it in a vector.

Implementation :

#include <bits/stdc++.h>
using namespace std;

vector<int> countAtEachDepth(string s)
{
    unordered_map<int, int> m; // hash map to store ->{
                               // depth -> no. of character}
    int d = 0; // d represents the running depth
    int maxd = 0; // maxd represents the max depth we
                  // encounter in our traversal
    for (auto& ch : s) // loop through the string
    {
        if (ch == '(') // if '(' we increment the depth
            d += 1;
        else if (ch == ')') // if ')' we decrement the depth
            d -= 1;
        else
            m[d] += 1; // incresing count of character at
                       // the current depth
        maxd = max(maxd, d); // storing max depth.
    }
    vector<int> res(maxd); // resultant vector
    for (auto& i : m) {
        int depth = i.first - 1;
        int val = i.second;
        res[depth] = val;
    }
    return res;
}

// Driver code
int main()
{
    string s = "(AA(AA(A))A)";
    vector<int> res = countAtEachDepth(s);
    for (auto& i : res) {
        cout << i << " ";
    }
    return 0;
}
Output

3 2 1

Time Complexity :  O(N)

Space Complexity :  O(N)

Comment
Mithlesh Upadhyay Published 28 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials