Problem Description
Given a tree of n nodes (indexed from 0 to n - 1) where node 0 is the root, each node has a label represented by a lowercase character in the string labels. The tree is represented using an array of edges, and there is exactly n - 1 edges. The task is to return an array ans of length n where ans[i] is the number of nodes in the subtree of node i (including itself) that share the same label as node i.
Key Insights
- The structure is guaranteed to be a tree (a connected, acyclic graph), allowing use of DFS without worrying about cycles.
- For every node, we need to count the occurrences of its own label in its subtree.
- Use DFS recursion with an adjacency list to traverse the tree and aggregate label frequencies from child nodes.
- Maintain a frequency count (e.g., using an array of size 26 for each lowercase letter) for each subtree and update the parent's counts accordingly.
Space and Time Complexity
Time Complexity: O(n) – each node and each edge is processed once. Space Complexity: O(n) – for the recursion stack and the adjacency list to represent the tree.
Solution
We solve the problem using Depth-First Search (DFS). First, construct an adjacency list from the given edges. Start DFS from the root node (0), and for each node initialize a frequency array for the 26 lowercase characters. Recursively, visit each child (skipping the parent to prevent revisiting) and accumulate the frequency counts returned from each subtree. After processing all children, update the frequency of the current node’s label, record this count as ans[node], and finally, return the frequency array to be merged with the parent's counts.