All problems
1059MediumHash TableTreeDepth-First SearchBreadth-First SearchDP on Trees

Visiting Every Marked Junction and Returning

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1443Minimum Time to Collect All Apples 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 n junctions numbered 0 through n - 1 is joined by the pipes pipes, one fewer pipe than there are junctions, with every junction reachable from every other and no loop anywhere. Walking a pipe takes one second, either way.

marked[i] says whether junction i needs visiting.

Start at junction 0, visit every marked junction, and return to junction 0. Return the fewest seconds it takes.

Examples

Example 1

Input
n = 4, pipes = [[0, 1], [1, 2], [0, 3]], marked = [false, false, true, false]
Output
4

Only junction 2 is marked, and reaching it means walking two pipes out and the same two back. The pipe to junction 3 has nothing marked beyond it and is never walked.

Example 2

Input
n = 3, pipes = [[0, 1], [0, 2]], marked = [false, true, true]
Output
4

Both junctions hanging off the start are marked, so each of the two pipes is walked out and back.

Example 3

Input
n = 1, pipes = [], marked = [true]
Output
0

The one junction is where the walk starts, so it is already visited and nothing needs walking.

Constraints

  • 1 <= n <= 10^5
  • pipes.length == n - 1
  • pipes[i].length == 2
  • 0 <= pipes[i][j] <= n - 1
  • The two ends of a pipe are different junctions.
  • marked.length == n

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 min_time(n: int, pipes: list[list[int]], marked: list) -> int:
Java
public int minTime(int n, int[][] pipes, boolean[] marked)
September 7
Apply