Python 1443.py
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
# an apple a day keeps Leetcode problems away ...
if not any(hasApple):
return 0
# collect edges
branches = defaultdict(list)
for a, b in edges:
branches[a].append(b)
branches[b].append(a)
seen = [ False ] * n
# count travelled edges including the incoming one (only if there is at least one apple)
def deeper(pos):
nonlocal seen
seen[pos] = True
# walk to our branch and back
step = 2
seconds = 0
for other in branches[pos]:
# ignore if already processed
if seen[other]:
continue
more = deeper(other)
if more > 0:
# walk this path to apples on sub-branches
# doesn't matter if there is an apple on the current branch
seconds += more
# add incoming edge (only if apples found in subtree, skip at root)
if pos != 0 and (seconds > 0 or hasApple[pos]):
seconds += 1 + 1
return seconds
return deeper(0)
Difficulty
and has an acceptance rate of about 63% (200k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Depth First Search
- Hash Table
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method minTime that computes the minimum number of seconds required to collect all apples in a tree and return to the starting node (node 0). The tree is defined by n vertices, a list of undirected edges, and a boolean list indicating which vertices contain an apple. The algorithm performs a depth-first traversal, accumulating the travel cost only for branches that lead to at least one apple.
Key Steps
The first logical block checks whether any apple exists in the entire tree. If none are present, the function returns immediately with zero cost.
if not any(hasApple):
return 0
Next, the code builds an adjacency list to represent the undirected tree. A defaultdict of lists is used so that each vertex can quickly access its neighboring vertices.
branches = defaultdict(list)
for a, b in edges:
branches[a].append(b)
branches[b].append(a)
A boolean list seen of length n tracks visited vertices during the traversal, preventing cycles in the undirected graph.
seen = [ False ] * n
The core of the algorithm is the nested deeper function, which performs a recursive depth-first search from a given vertex pos. The function marks the current vertex as visited, initializes a step counter of two (representing the round-trip cost for the current edge), and iterates over all neighboring vertices.
def deeper(pos):
nonlocal seen
seen[pos] = True
# walk to our branch and back
step = 2
seconds = 0
for other in branches[pos]:
# ignore if already processed
if seen[other]:
continue
more = deeper(other)
if more > 0:
# walk this path to apples on sub-branches
# doesn't matter if there is an apple on the current branch
seconds += more
After processing all children, the function decides whether to add the cost of the incoming edge. The edge cost is added only if the current vertex is not the root (pos != 0) and either the subtree contains apples (seconds > 0) or the current vertex itself holds an apple (hasApple[pos]). The addition of 1 + 1 accounts for the forward and backward traversal of that edge.
# add incoming edge (only if apples found in subtree, skip at root)
if pos != 0 and (seconds > 0 or hasApple[pos]):
seconds += 1 + 1
return seconds
Finally, the traversal is initiated from the root node (0), and the accumulated travel time is returned.
return deeper(0)
Edge Cases Handled
When the tree contains no apples at all, the early any check short-circuits the computation, returning zero without constructing the adjacency list or performing any recursion. This avoids unnecessary work for the trivial case.
If the root node itself contains an apple, the algorithm still correctly accounts for the travel cost of its children while omitting any additional cost for the root’s incoming edge, because the condition pos != 0 prevents adding the extra 1 + 1 at the root level.
Leaf vertices are naturally handled by the recursion: a leaf that does not contain an apple yields a more value of zero, causing its parent to ignore that branch entirely. Conversely, a leaf with an apple triggers the addition of the edge cost when the recursion unwinds, ensuring the path to that leaf is counted.
Subtrees that contain no apples are pruned efficiently. The recursive call returns zero for such subtrees, and the parent’s loop adds nothing to seconds. Consequently, no travel time is incurred for branches that lead to empty subtrees.
Performance Optimizations
The adjacency list is built using a defaultdict, which provides O(1) amortized insertion for each edge and eliminates the need for explicit existence checks when appending neighbors. This choice streamlines the graph construction phase.
The seen list serves as a lightweight visited marker, enabling constant-time checks to avoid revisiting nodes in the undirected graph. By marking vertices as soon as they are entered, the algorithm prevents redundant traversals and guarantees that each edge is examined at most twice (once from each endpoint).
The early exit when no apples are present eliminates all subsequent processing, saving both time and memory for that scenario.
During the depth-first search, the function aggregates travel time only when a subtree contributes a positive more value. This conditional accumulation acts as a form of lazy evaluation, ensuring that the algorithm does not waste cycles on branches that ultimately do not affect the final answer. The selective addition of the incoming edge cost (1 + 1) further reduces unnecessary arithmetic for the root and for empty subtrees.
Overall, the combination of early termination, adjacency list efficiency, visited tracking, and selective cost accumulation yields a solution that scales linearly with the number of vertices and edges in the tree.
ELI5 - Simplified Explanation
Imagine a giant tree made of paths that connect different houses together. Some of those houses have a delicious apple sitting inside, and others are empty. The goal is to start at the very first house and visit every single place where an apple is hiding. After finding an apple, the traveler has to walk all the way back to the start.
Tracking the path is like making a map of which houses connects to which. The code starts at the beginning and looks at every connection to see where it leads. It acts like a curious explorer wandering down each path to check if there is an apple waiting at the end. Because the traveler has to walk to the apple and then walk back to the start to share it, every path adds up in time.
The explorer keeps a little checklist to make sure they do not get lost by visiting the same house twice. When the explorer steps into a path, they add up how many minutes it takes to reach the apples. If a house has an apple or if there is an apple further down that specific path, the explorer counts the time for those walks. Once all the apples are found and the counts are gathered, that total number tells exactly how much time was spent walking around the tree.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | |||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| martianoff | Scala | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| martianoff | Scala | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1360: Number of Days Between Two Dates
- problem 1576: Replace All ?'s to Avoid Consecutive Repeating Characters
- problem 1716: Calculate Money in Leetcode Bank
- problem 2409: Count Days Spent Together
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2644: Find the Maximum Divisibility Score
- problem 1110: Delete Nodes And Return Forest
- problem 1296: Divide Array in Sets of K Consecutive Numbers
- problem 1669: Merge In Between Linked Lists
- problem 458: Poor Pigs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality