Collect Coins in a Tree — LeetCode 2603 Python Solution

HardTreeGraphTopological SortArray
Problem
#2603
Reading time
4 min

The problem

There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given an integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Example

Input
coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]
Output
2
Explanation
Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2.

Python solution

Python
class Solution:
    def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int:
        g = defaultdict(set)
        for a, b in edges:
            g[a].add(b)
            g[b].add(a)
        n = len(coins)
        q = deque(i for i in range(n) if len(g[i]) == 1 and coins[i] == 0)
        while q:
            i = q.popleft()
            for j in g[i]:
                g[j].remove(i)
                if coins[j] == 0 and len(g[j]) == 1:
                    q.append(j)
            g[i].clear()
        for k in range(2):
            q = [i for i in range(n) if len(g[i]) == 1]
            for i in q:
                for j in g[i]:
                    g[j].remove(i)
                g[i].clear()
        return sum(len(g[a]) > 0 and len(g[b]) > 0 for a, b in edges) * 2

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes auxiliary

Pattern: Topological Sort

Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 2603. Collect Coins in a Tree is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.

The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2603. Collect Coins in a Tree?
LeetCode 2603. Collect Coins in a Tree is rated Hard on LeetCode.
What is the time complexity of LeetCode 2603. Collect Coins in a Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2603. Collect Coins in a Tree?
The Python solution on this page uses O(n), where n is the number of nodes auxiliary space.
What topics does LeetCode 2603. Collect Coins in a Tree cover?
LeetCode 2603. Collect Coins in a Tree is tagged Tree, Graph, Topological Sort and Array 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