Collect Coins in a Tree - 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.

You are also given an array coins of size n where coins[i] can be either 0 or 1, where 1 indicates the presence of a coin in the vertex i.

Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times:

  • Collect all the coins that are at a distance of at most 2 from the current vertex, or
  • Move to any adjacent vertex in the tree.

Find the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex.

Note: If you pass an edge several times, you need to count it into the answer several times.

Input & Output

Example 1 — Simple Tree
$ Input: coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]
Output: 2
💡 Note: Tree is a straight line. Starting from node 2, we can collect coin at node 0 (distance 2) and coin at node 5 (distance 3 via node 3). We need to visit node 3 and return, so 2 edges total.
Example 2 — Star Configuration
$ Input: coins = [0,0,0,1,1,1], edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
Output: 6
💡 Note: Central node 0 connects to all others. Coins are at nodes 3,4,5. From node 0, we can collect all coins at distance 1. We need to visit each coin node and return: 3×2 = 6 edges.
Example 3 — No Coins
$ Input: coins = [0,0,0], edges = [[0,1],[1,2]]
Output: 0
💡 Note: No coins to collect, so no movement needed.

Constraints

  • 1 ≤ n ≤ 3 × 104
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • edges represents a valid tree
  • coins[i] is either 0 or 1

Visualization

Tap to expand
Collect Coins in Tree: Distance-2 Collection RuleTree with Coins01💰23💰Distance ≤ 2Collection ZoneYouFrom any position, collect coins within distance 2Goal: Find minimum edges for round trip
Understanding the Visualization
1
Input
Tree with coins marked at specific nodes
2
Collection Rule
From any node, collect coins within distance 2
3
Optimal Path
Find minimum edges for round trip collecting all coins
Key Takeaway
🎯 Key Insight: Since coins can be collected from distance 2, we can prune many unnecessary leaf nodes to find the minimal essential tree structure
Asked in
Google 45 Meta 38 Amazon 32 Apple 28
28.0K Views
Medium Frequency
~35 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen