Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2603: Collect Coins in a Tree

In this guide, we solve Leetcode #2603 Collect Coins in a Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Tree, Graph, Topological Sort, Array

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

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

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

The time complexity is O(n)O(n)O(n) and the space complexity is O(n)O(n)O(n), where nnn is the number of nodes. The space complexity is O(n)O(n)O(n), where nnn is the number of nodes.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy