Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

HackerEarth Nodes in a subtree problem solution

YASH PAL, 31 July 2024
In this HackerEarth Nodes in a subtree problem solution, You are given a rooted tree that contains N nodes. Each node contains a lowercase alphabet.
You are required to answer Q queries of type u,c, where u is an integer and c is a lowercase alphabet. The count of nodes in the subtree of the node u containing c is considered as the answer of all the queries. 
HackerEarth Nodes in a subtree problem solution

HackerEarth Nodes in a subtree problem solution.

#include<bits/stdc++.h>
using namespace std;
int cnt[100005][26], n;
vector<int> adj[100005];
string s;
void dfs(int u, int parent)
{
int i;
for(i = 0; i < 26; i ++)
cnt[u][i] = 0;
cnt[u][s[u - 1] - 'a'] ++;
for(auto v: adj[u])
{
if(v == parent)
continue;
dfs(v, u);
for(i = 0; i < 26; i ++)
cnt[u][i] += cnt[v][i];
}
}
int main()
{
int q, i;
cin >> n >> q;
cin >> s;
for(i = 0; i < n - 1; i ++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, 0);
while(q --)
{
int u;
char c;
cin >> u >> c;
cout << cnt[u][c - 'a'] << endl;
}
return 0;
}
coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes