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 :
- If we encounter ‘(‘ character then depth increases.
- If we encounter ‘)’ character then depth decreases.
- If we encounter ‘A’ character then this character correspond to the depth ‘d’ and we increase the value in hash map by 1.
- 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;
}
Time Complexity : O(N)
Space Complexity : O(N)