All problems
0978HardArrayTreeGraph TheoryTopological Sort

Shortest Round Trip to Sweep Every Parcel

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2603Collect Coins in a Tree

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A network of hubs is given as a tree: edges lists the links, and coins[i] is 1 when hub i holds a parcel and 0 otherwise.

A van starts at any hub it likes and must finish back where it started. A parcel is swept when the van visits some hub no more than two links away from the parcel's hub.

Every link travelled counts, and travelling the same link again counts again. Return the fewest links the round trip can travel while sweeping every parcel.

Examples

Example 1

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

The hubs run in a line of four with parcels at the two ends. Standing at either middle hub sweeps both ends, since each is within two links, so the van need not move at all.

Example 2

Input
coins = [1, 0, 0, 0, 0, 0, 0, 1], edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
Output
6

The line is eight hubs long with parcels at the ends. The van must reach within two links of each end, which means covering the two middle links and walking them both ways.

Example 3

Input
coins = [0], edges = []
Output
0

A single hub with no parcel means there is nothing to sweep.

Constraints

  • 1 <= coins.length <= 3 * 10^4
  • 0 <= coins[i] <= 1
  • edges.length == coins.length - 1
  • edges[i].length == 2
  • 0 <= edges[i][0] <= coins.length - 1
  • 0 <= edges[i][1] <= coins.length - 1
  • The two hubs on a link are different
  • The links form a tree

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def collect_the_coins(coins: list[int], edges: list[list[int]]) -> int:
Java
public int collectTheCoins(int[] coins, int[][] edges)
September 7
Apply