Leetcode 1519: Number of Nodes in the Sub-Tree With the Same Label

grid47
grid47
Exploring patterns and algorithms
Jun 8, 2024 7 min read

You are given a tree with n nodes, where each node has a label, and your task is to find the number of nodes in the subtree rooted at each node that have the same label as that node.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n`, an array of edges, and a string of labels.
Example: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], labels = 'abacba'
Constraints:
• 1 <= n <= 10^5
• edges.length == n - 1
• 0 <= ai, bi < n
• ai != bi
• labels.length == n
• labels consists only of lowercase English letters.
Output: Return an array where each element `ans[i]` represents the number of nodes in the subtree rooted at node `i` that have the same label as node `i`.
Example: [2, 1, 1, 1, 1, 1]
Constraints:
• The answer is an array of size `n`.
Goal: The goal is to traverse the tree and, for each node, count how many nodes in its subtree have the same label.
Steps:
• Step 1: Build the tree using an adjacency list from the edges.
• Step 2: Perform a Depth First Search (DFS) traversal from the root to visit each node.
• Step 3: For each node, count the number of nodes with the same label in its subtree, including itself.
• Step 4: Return the result as an array.
Goal: The tree structure is guaranteed to be valid with no cycles, and the input constraints should be respected.
Steps:
• The tree is connected and acyclic.
• Subtree counting should be efficient for large inputs (n up to 10^5).
Assumptions:
• The tree is rooted at node 0.
• Each node has a unique label.
Input: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], labels = 'abacba'
Explanation: Node 0 has label 'a', and its subtree contains node 2 with label 'a', making the count 2. Similarly, other nodes' subtrees are evaluated.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus