Collect Coins in a Tree - Problem

๐ŸŒณ Collect Coins in a Tree

Imagine you're a treasure hunter exploring a mystical tree-shaped network of caves. Each cave (node) may contain a magical coin, and you can collect all coins within a distance of 2 from your current position without moving!

You start at any cave of your choice and can perform two operations:

  • Collect: Gather all coins within distance โ‰ค 2 from your current cave
  • Move: Travel to any directly connected cave (costs 1 edge traversal)

Your mission: Find the minimum number of edges you need to traverse to collect all coins and return to your starting cave. Remember, each edge traversal counts separately - if you pass through the same edge multiple times, count it each time!

Input: An integer n (number of caves), a 2D array edges defining the tree structure, and a binary array coins where coins[i] = 1 means cave i contains a coin.

Output: Return the minimum number of edge traversals needed.

Input & Output

example_1.py โ€” Basic Tree
$ Input: n = 3, coins = [1,0,0], edges = [[0,1],[1,2]]
โ€บ Output: 0
๐Ÿ’ก Note: We can start at node 1 and collect the coin at node 0 (distance 1 โ‰ค 2) without moving. Since node 0 is the only coin, we're done and don't need to move at all.
example_2.py โ€” Linear Chain
$ Input: n = 4, coins = [1,0,0,1], edges = [[0,1],[1,2],[2,3]]
โ€บ Output: 2
๐Ÿ’ก Note: Start at node 1. Collect coin from node 0 (distance 1). Move to node 2 (1 edge), then collect coin from node 3 (distance 1). Return to node 1 (1 edge). Total: 2 edges.
example_3.py โ€” All Coins
$ Input: n = 2, coins = [1,1], edges = [[0,1]]
โ€บ Output: 0
๐Ÿ’ก Note: From either starting node, we can collect both coins since they're within distance 2 of each other. No movement needed.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through all nodes and edges for trimming operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for adjacency list and degree arrays

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 3 ร— 104
  • coins.length == n
  • coins[i] is either 0 or 1
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 โ‰ค ai, bi < n
  • ai โ‰  bi
  • The edges represent a valid tree structure
  • There is at least one coin in the tree
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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