Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

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 solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes