Problem 1443

Abstract / Summary

Given a tree with apples on some nodes, find the least time needed to collect all apples starting and ending at the same node.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
41 lines | 1325 bytes | submitted December 6, 2023 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.47

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 15 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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