Number of Nodes in the Sub-Tree With the Same Label Problem
Description
LeetCode Problem 1519.
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).
The edges array is given on the form edges[i] = [a_i, b_i], which means there is an edge between nodes a_i and b_i in the tree.
Return an array of size n where ans[i] is the number of nodes in the subtree of the i^th node which have the same label as node i.
A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.
Example 1:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
Output: [2,1,1,1,1,1,1]
Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
Example 2:

Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
Output: [4,2,1,1]
Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
Example 3:

Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
Output: [3,2,1,1,1]
Constraints:
1 <= n <= 10^5edges.length == n - 1edges[i].length == 20 <= a_i, b_i < na_i != b_ilabels.length == nlabelsis consisting of only of lowercase English letters.
Solution
Approach: DFS with Global Label Counters
Running a separate count from every node would be O(n2). Instead, notice what a depth-first search does: once it enters node i, it visits exactly the nodes of i's subtree before it leaves i.
So keep one global array count[26] of how many nodes of each label the DFS has visited so far. For node i with label c:
- On entering
i, rememberbefore = count[c], then countiitself. - Visit all children (every neighbor except the parent, since the edges are undirected).
- On leaving
i,count[c] - beforeis the number of nodes labeledcthat were visited insidei's subtree, includingi. That isans[i].
The tree is given as an undirected edge list, so we build adjacency lists and pass the parent along to avoid walking back up.
Complexity: O(n) time and O(n) space for the adjacency lists and the recursion stack (the 26 counters are constant).
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
graph = [[] for _ in range(n)]
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
count = [0] * 26 # how many nodes of each label the DFS has visited so far
ans = [0] * n
def dfs(i, parent):
k = ord(labels[i]) - ord("a")
before = count[k]
count[k] += 1
for j in graph[i]:
if j != parent:
dfs(j, i)
# everything counted since entering i lies in i's subtree
ans[i] = count[k] - before
dfs(0, -1)
return ans