Minimum Time to Collect All Apples in a Tree

MediumGraphsdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An undirected tree has n vertices labeled 0 to n - 1, connected by the n - 1 pairs in edges (each [a, b] is an undirected edge). hasApple[i] is true when vertex i holds an apple. You start at vertex 0, walk along edges (each traversal of an edge costs 1 second), pick up every apple, and must finish back at vertex 0. Picking up an apple is free. Return the minimum total time. If there are no apples (or only one at vertex 0), the answer is 0.

Examples

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
Output: 8
You must visit 2, 4, and 5. Edges 0-1, 1-4, 1-5, and 0-2 are each walked twice: 4 * 2 = 8.
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
Output: 6
Apples at 2 and 5 require edges 0-1, 1-5, and 0-2, each walked there and back.
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
Output: 0
No apples, so you never leave vertex 0.

Constraints

  • 1 <= n <= 10^5
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= a, b <= n - 1
  • edges form a tree (edge endpoints may be listed in either order)
  • hasApple.length == n

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems