#2603

Collect Coins in a Tree

Hard
ArrayTreeGraph TheoryTopological SortGraph Traversal (DFS, BFS)Tree PruningDynamic Programming (for more complex variations)
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution focuses on pruning the tree by removing unnecessary nodes (leaves without coins) and calculating the minimum distance needed to collect all coins efficiently. This reduces the number of nodes we need to traverse.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build the graph from the edges.
  2. 2Step 2: Remove all leaves that do not have coins until no such leaves remain.
  3. 3Step 3: Perform a DFS from any remaining node to calculate the total distance needed to collect all coins and return.
solution.py28 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def collect_coins_optimal(coins, edges):
5    graph = defaultdict(list)
6    for a, b in edges:
7        graph[a].append(b)
8        graph[b].append(a)
9
10    leaves = deque([i for i in range(len(coins)) if coins[i] == 0])
11    while leaves:
12        leaf = leaves.popleft()
13        for neighbor in graph[leaf]:
14            graph[neighbor].remove(leaf)
15            if len(graph[neighbor]) == 1 and coins[neighbor] == 0:
16                leaves.append(neighbor)
17        graph.pop(leaf, None)
18
19    if not graph:
20        return 0
21
22    def dfs(node):
23        total_distance = 0
24        for neighbor in graph[node]:
25            total_distance += dfs(neighbor) + 1
26        return total_distance
27
28    return 2 * dfs(next(iter(graph)))

Complexity note: The complexity is linear because we traverse each node and edge a constant number of times during the leaf removal and DFS traversal.

  • 1Pruning the tree by removing unnecessary nodes can significantly reduce the problem's complexity.
  • 2Understanding how to traverse trees efficiently is crucial for solving problems involving graphs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.