Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Collect Coins in a Tree

XPChallenge Points: 30
levelLevel: Hard

You are given a tree with n nodes (0 to n-1). Each node may or may not have a coin.
You can start at any node.

You are allowed to perform two actions:

  1. Collect coins that are located within distance ≤ 2 from your current node.

  2. Move to any directly connected (adjacent) node.

Your goal is to collect every coin in the entire tree, and then return back to your starting node, while minimizing the total number of edge moves.
If you move across the same edge multiple times, each move counts.

Return the minimum number of edge movements needed.

Example 1:

Input: coins = [1, 1, 0] edges = [[0,1],[1,2]]

Output: 2

Explanation:

Start from node 1. Collect coins at 0 and 1 immediately (distance ≤ 2). Move to node 2 if needed and return → total moves = 2.

Example 2:

Input: coins = [0,1,1,0] edges = [[0,1],[1,2],[2,3]]

Output: 2

Explanation:

Start at node 1 or 2. Collect both coins, walk minimal steps and return.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result