MediumNo. 2477

Minimum Fuel Cost to Report to the Capital — LeetCode 2477 Python Solution

Topics
Tree, Depth-First Search, Breadth-First Search, Graph
Reading time
4 min

The problem

There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0.

Example

Input
roads = [[0,1],[0,2],[0,3]], seats = 5
Output
3
Explanation
- Representative1 goes directly to the capital with 1 liter of fuel.

Python solution

PythonSolution
class Solution:
    def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:
        def dfs(a: int, fa: int) -> int:
            nonlocal ans
            sz = 1
            for b in g[a]:
                if b != fa:
                    t = dfs(b, a)
                    ans += ceil(t / seats)
                    sz += t
            return sz

        g = defaultdict(list)
        for a, b in roads:
            g[a].append(b)
            g[b].append(a)
        ans = 0
        dfs(0, -1)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2477. Minimum Fuel Cost to Report to the Capital is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2467Most Profitable Path in a TreeMedium
1361Validate Binary Tree NodesMedium
1377Frog Position After T SecondsHard
0207Course ScheduleMedium
0210Course Schedule IIMedium
0310Minimum Height TreesMedium

Frequently asked questions

How hard is LeetCode 2477. Minimum Fuel Cost to Report to the Capital?

LeetCode 2477. Minimum Fuel Cost to Report to the Capital is rated Medium on LeetCode.

What is the time complexity of LeetCode 2477. Minimum Fuel Cost to Report to the Capital?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2477. Minimum Fuel Cost to Report to the Capital?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2477. Minimum Fuel Cost to Report to the Capital cover?

LeetCode 2477. Minimum Fuel Cost to Report to the Capital is tagged Tree, Depth-First Search, Breadth-First Search and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.