Number of Nodes in the Sub-Tree With the Same Label — LeetCode 1519 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchHash TableCounting
Problem
#1519
Reading time
3 min

The problem

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.

Example

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.

Python solution

Python
class Solution:
    def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
        def dfs(i, fa):
            ans[i] -= cnt[labels[i]]
            cnt[labels[i]] += 1
            for j in g[i]:
                if j != fa:
                    dfs(j, i)
            ans[i] += cnt[labels[i]]

        g = defaultdict(list)
        for a, b in edges:
            g[a].append(b)
            g[b].append(a)
        cnt = Counter()
        ans = [0] * n
        dfs(0, -1)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label?
LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label is rated Medium on LeetCode.
What is the time complexity of LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label cover?
LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview