Problem 1519

Abstract / Summary

Given a tree and node labels, count nodes in each subtree that share the same label as the root of that subtree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1519.py

class Solution:
    def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
        result = [ 0 ] * n

        # build tree
        next = defaultdict(list)
        for a, b in edges:
            next[a].append(b)
            next[b].append(a)

        # already visited
        seen = set()

        def deeper(node):
            # don't visit twice
            nonlocal seen, result
            if node in seen:
                return None
            seen.add(node)

            have = defaultdict(int)
            for children in next[node]:
                add = deeper(children)
                if add:
                    for a in add:
                        have[a] += add[a]

            # node's label
            current        = labels[node]
            have[current] += 1
            result[node]   = have[current]
            return have

        deeper(0)
        return result
35 lines | 957 bytes | submitted December 8, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (100k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Counting
  • Depth First Search
  • Hash Table
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a method countSubTrees. The method receives the number of nodes n, an edge list describing an undirected tree, and a string labels where each character denotes the label of the corresponding node. The goal is to compute, for every node, how many nodes in its subtree (including itself) share the same label as the node. The algorithm builds an adjacency representation, performs a depth-first traversal from the root (node 0), aggregates label frequencies in a dictionary, and stores the required counts in the result list.

Building the adjacency structure

next = defaultdict(list)
for a, b in edges:
    next[a].append(b)
    next[b].append(a)

The code creates a defaultdict of lists named next. For each undirected edge [a, b], both directions are recorded, allowing constant-time access to a node’s neighbors during traversal. This representation is compact and avoids the need for separate parent-child bookkeeping.

Tracking visited nodes

seen = set()

A set called seen records nodes that have already been visited. Because the tree is undirected, the adjacency list contains back-edges to the parent. The seen set prevents the recursive function from revisiting a node, thereby guaranteeing termination and correctly handling the inherent bidirectional connections.

Recursive depth-first aggregation

def deeper(node):
    nonlocal seen, result
    if node in seen:
        return None
    seen.add(node)

    have = defaultdict(int)
    for children in next[node]:
        add = deeper(children)
        if add:
            for a in add:
                have[a] += add[a]

    current = labels[node]
    have[current] += 1
    result[node] = have[current]
    return have

The inner function deeper performs a post-order traversal. It first checks the seen set to avoid reprocessing a node. A fresh defaultdict(int) called have is created to accumulate label frequencies for the current subtree. For each neighbor (children) of the current node, the function recursively obtains the neighbor’s frequency map (add). If a map is returned, its entries are merged into have. The merging loop adds each label count from the child’s map to the parent’s map, ensuring that the parent’s map reflects the entire subtree processed so far.

After processing all children, the node’s own label (current) is incremented in have. The count for the node’s label is then stored in result[node]. Finally, the complete frequency map for the subtree rooted at node is returned to the caller.

Initiating the traversal

deeper(0)
return result

The traversal starts from node 0, which is treated as the root of the tree. Because the tree is connected, this single call reaches every node. The final result list, now populated with the required counts, is returned to the caller.

Edge-case handling

The algorithm gracefully handles several edge conditions:

  • Single-node tree: When n equals 1, the adjacency list contains no edges. The deeper function is called on node 0, have receives the node’s label, and result[0] becomes 1, correctly reflecting that the sole node’s subtree contains exactly one occurrence of its label.

  • Repeated labels: The frequency dictionary have aggregates counts for any label that appears multiple times in a subtree. The merging loop adds counts from each child, so nodes with many identical labels receive the correct total.

  • Disconnected input (theoretically): Although the problem guarantees a tree, the seen set ensures that even if the input contained extra components, the recursion would stop after exhausting reachable nodes from the root, preventing infinite loops.

  • Empty label string: If labels were an empty string (which would be inconsistent with n), the code would attempt to index labels[node] and raise an exception. However, within the problem constraints, labels always has length n, so the implementation safely accesses each character.

Performance optimizations

The implementation incorporates several choices that reduce overhead:

  • Use of defaultdict for adjacency and frequency maps eliminates the need for explicit existence checks before appending neighbors or incrementing counts. This yields concise code and avoids conditional branches inside tight loops.

  • Early exit on visited nodes (if node in seen: return None) prevents unnecessary recursion into already processed branches. Because each node is added to seen exactly once, the total number of recursive calls equals the number of nodes, guaranteeing linear work.

  • Returning None for already visited nodes allows the caller to skip the merging loop entirely for those cases, avoiding the cost of iterating over an empty dictionary.

  • In-place accumulation: The have dictionary for a node is built directly from its children’s dictionaries without creating intermediate copies. The merging loop updates the parent’s dictionary in place, minimizing memory allocations.

  • Single pass traversal: By performing a post-order depth-first search, the algorithm computes the required counts in one traversal. No separate passes are needed to propagate label frequencies upward, which keeps the runtime proportional to the size of the tree.

Overall, the code delivers the desired result with a straightforward depth-first strategy, leveraging Python’s dynamic containers to keep the implementation compact while maintaining efficient execution for typical tree sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big family tree made of colorful wooden blocks. Every block has a letter painted on it. You have a bunch of sticks connecting these blocks together so they branch out like a real tree. The goal is to look at each block and count how many blocks in the entire branch below it share the same color letter as that block.

First, a group of empty buckets is set up to keep track of the counts for every single block in the tree. Then, the connection sticks are organized so that every block knows which other blocks are attached to it.

The computer starts at the very top block and goes down along the branches. It keeps a secret list of blocks it has already looked at so it does not get confused and visit the same place twice. As it travels down to the very end of a branch, it starts counting the letters it finds on the way back up.

When the computer is at a specific block, it asks all the blocks below it, what letters do you have? It gathers all those answers together and adds its own letter to the pile. Once it knows how many letters match its own, it writes that number down in the bucket for that specific block. This happens over and over, moving from the tiny ends of the branches all the way back to the main starting block at the top, until every block has its final answer written down.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.41 | σ = 0.87

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
FelixFan1122 Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
FelixFan1122 Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
25 links | 15 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality