Similar Problems
Similar Problems not available
Minimum Time To Collect All Apples In A Tree - Leetcode Solution
Companies:
LeetCode: Minimum Time To Collect All Apples In A Tree Leetcode Solution
Difficulty: Medium
Topics: hash-table tree depth-first-search breadth-first-search
Problem Statement:
Given a tree in which each vertex represents a fruit-bearing apple tree, you need to collect all the apples without skipping your instructions.
The apple tree is represented by an integer array where the value of the ith element is the location of the ith apple tree. You can start at any vertex of the tree and visit each vertex in any order.
You can collect apples at any vertex as long as you’ve reached the equipment that’s installed there.
Return the minimum time in seconds you need to collect all apples in the tree starting at vertex 0.
Solution:
The problem statement asks us to find the minimum time required to collect all apples in the tree. We can solve this problem using the Breadth First Search algorithm.
We start from the root node (node 0) and traverse the tree to collect the apples. We maintain a variable called distance, which represents the distance traveled so far, and a boolean array called visited, which represents whether a particular node has been visited or not.
We use a priority queue that stores the next node that we should visit based on the distance, with the minimum distance always on top.
During the traversal, we check if the current node has an apple tree. If yes, we mark it as visited and add the distance to the total distance.
We continue the traversal until we visit all the nodes with apple trees and return the total distance traveled.
Algorithm:
-
Initialize distance = 0 and visited[0] = true.
-
Create a priority queue pq and push the root node 0 with distance 0.
-
While pq is not empty:
a. Pop the node with minimum distance.
b. If node i has an apple tree and has not been visited yet, add the distance to the total distance and mark visited[i] as true.
c. For each neighbor j of node i:
i. If the neighbor j has not been visited yet, push it to pq with the distance traveled so far plus the distance between i and j.
-
Return the total distance traveled.
Time Complexity: O(nlogn), where n is the number of nodes in the tree.
Space Complexity: O(n), where n is the number of nodes in the tree.
Implementation:
Here’s the implementation of the above algorithm in Python:
import heapq
class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int: visited = [False] * n distance = 0 graph = [[] for _ in range(n)]
for i in range(len(edges)):
u, v = edges[i]
graph[u].append(v)
graph[v].append(u)
pq = [(0, 0)]
visited[0] = True
while pq:
dist, node = heapq.heappop(pq)
if hasApple[node] and not visited[node]:
visited[node] = True
distance += dist
for neighbor in graph[node]:
if not visited[neighbor]:
heapq.heappush(pq, (dist + 1, neighbor))
return distance * 2
Minimum Time To Collect All Apples In A Tree Solution Code
1There are n apples in a tree, and each apple has a unique value. You are given an integer array tree of size n, where tree[i] is the value of the ith apple in the tree.
2
3You start at the root of the tree and collect apples as you move down the tree. The value of an apple at each node is given by tree[node]. You can only move to adjacent nodes (children of the current node) if tree[node] is equal to tree[parent], where parent is the index of the current node's parent.
4
5Return the minimum number of moves required to collect all apples in the tree.
6
7
8
9int minTime(vector<int>& tree) {
10 // Base case
11 if (tree.empty()) {
12 return 0;
13 }
14 // DFS
15 int res = 0;
16 stack<pair<int, int>> stk; // {node, parent}
17 stk.push({0, -1});
18 while (!stk.empty()) {
19 auto [node, parent] = stk.top();
20 stk.pop();
21 // Check if current node has been visited
22 if (tree[node] != tree[parent]) {
23 res++;
24 }
25 // Visit children
26 for (int child : {node * 2 + 1, node * 2 + 2}) {
27 if (child < tree.size() && tree[child] == tree[node]) {
28 stk.push({child, node});
29 }
30 }
31 }
32 return res;
33 }