Leetcode 1443: Minimum Time to Collect All Apples in a Tree

grid47
grid47
Exploring patterns and algorithms
Jun 15, 2024 7 min read

You are given an undirected tree with n vertices numbered from 0 to n-1. Some vertices in this tree contain apples. Each edge in the tree requires 1 second to traverse. Starting at vertex 0, determine the minimum time required to collect all apples and return to vertex 0. The tree structure is described by the array edges, where edges[i] = [ai, bi] indicates an edge between vertices ai and bi. Additionally, the array hasApple specifies whether a vertex contains an apple (true) or not (false).
Problem
Approach
Steps
Complexity
Input: The number of vertices `n`, the list of edges representing the tree, and the boolean array `hasApple`.
Example: Input: n = 5, edges = [[0,1],[0,2],[1,3],[1,4]], hasApple = [false,true,true,false,false]
Constraints:
• 1 <= n <= 10^5
• edges.length == n - 1
• 0 <= ai, bi < n
• Each vertex is part of exactly one connected component.
• hasApple.length == n
Output: An integer representing the minimum time in seconds to collect all apples and return to vertex `0`.
Example: Output: 6
Constraints:
• The output must be a non-negative integer.
Goal: Find the minimum traversal time to collect all apples and return to the starting point.
Steps:
• Construct a graph from the edges.
• Use a Depth-First Search (DFS) to traverse the tree starting from vertex `0`.
• For each subtree, calculate the time required to collect apples.
• Avoid unnecessary traversal if no apples are present in a subtree.
Goal: Ensure efficient computation for large inputs.
Steps:
• Avoid revisiting nodes by using a `visited` array.
• Ensure the solution handles up to `10^5` vertices within reasonable time.
Assumptions:
• The tree is connected and acyclic.
• The input tree has exactly `n-1` edges.
Input: Input: n = 6, edges = [[0,1],[0,2],[1,3],[2,4],[2,5]], hasApple = [false,false,true,false,true,true]
Explanation: The optimal path involves visiting vertices 2, 4, and 5. The total time is `8` seconds.

Input: Input: n = 4, edges = [[0,1],[0,2],[1,3]], hasApple = [false,false,false,false]
Explanation: No apples exist, so the output is `0`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus