Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerEarth Nodes in a subtree problem solution

YASH PAL, 31 July 202414 February 2026
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 solutions HackerEarth HackerEarth

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes