Minimum Fuel Cost to Report to the Capital solution and explanation
9 more videos on this problem
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - PythonNeetCodeIO · 12:40 · 15K views
2477. Minimum Fuel Cost to Report to the Capital | Weekly 320 | LeetCode 2477Bro Coders · 10:36 · 8K views
Leetcode 2477 Minimum Fuel Cost to Report to the Capital | SDE Sheet belowCoding Decoded · 11:55 · 2K views
2477. Minimum Fuel Cost to Report to the Capital | LeetCode MediumDeep Tech · 13:24 · 1K views
2477. Minimum Fuel Cost to Report to the Capital (Leetcode Medium)Programming Live with Larry · 9:36 · 1K views
Minimum Fuel Cost to Report to the Capital - Graph - Leetcode 2477 - PythonCheatCode Ninja · 7:35 · 1K views
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - PythonTechError · 12:30 · 604 views
Daily Leetcode #1048: Feb 12, 2023 - 2477. Minimum Fuel Cost to Report to the CapitalProgramming Live with Larry · 12:05 · 316 views
LeetCode 2477. Minimum Fuel Cost to Report to the Capital | DFS | C++Coding Charms · 13:19 · 274 views
2477. Minimum Fuel Cost to Report to the Capital | JavaScript | BFS | O(N) LeetCode Daily ChallengeLeetCodeWithMonu · 16:42 · 188 views
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. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.
There is a meeting for the representatives of each city. The meeting is in the capital city.
There is a car in each city. You are given an integer seats that indicates the number of seats in each car.
A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.
Return the minimum number of liters of fuel to reach the capital city.
Example 1:
Input: roads = [[0,1],[0,2],[0,3]], seats = 5 Output: 3 Explanation: - Representative1 goes directly to the capital with 1 liter of fuel. - Representative2 goes directly to the capital with 1 liter of fuel. - Representative3 goes directly to the capital with 1 liter of fuel. It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed.
Example 2:
Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2 Output: 7 Explanation: - Representative2 goes directly to city 3 with 1 liter of fuel. - Representative2 and representative3 go together to city 1 with 1 liter of fuel. - Representative2 and representative3 go together to the capital with 1 liter of fuel. - Representative1 goes directly to the capital with 1 liter of fuel. - Representative5 goes directly to the capital with 1 liter of fuel. - Representative6 goes directly to city 4 with 1 liter of fuel. - Representative4 and representative6 go together to the capital with 1 liter of fuel. It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed.
Example 3:
Input: roads = [], seats = 1 Output: 0 Explanation: No representatives need to travel to the capital city.
Constraints:
1 <= n <= 105roads.length == n - 1roads[i].length == 20 <= ai, bi < nai != biroadsrepresents a valid tree.1 <= seats <= 105
Approach overview
Problem Overview: You are given n cities connected by n-1 roads forming a tree. Each city has one representative who must travel to the capital (city 0). Cars have seats capacity and consume one unit of fuel per road traveled. Representatives can share cars along the way. The task is to compute the minimum total fuel required for everyone to reach the capital.
Approach 1: DFS to Aggregate Representatives (O(n) time, O(n) space)
Treat the road network as a tree rooted at the capital. Use Depth-First Search to traverse from the capital and compute how many representatives exist in each subtree. Every node contributes one representative. When returning from a child subtree, calculate the number of cars required to move those representatives to the parent using ceil(representatives / seats). Each of those cars consumes one unit of fuel for the edge to the parent. Summing this value across all edges gives the minimum fuel. The key insight is that representatives naturally merge while moving upward, so the optimal strategy is always to combine them as early as possible in the tree.
Approach 2: BFS with Leaf Processing (O(n) time, O(n) space)
Build an adjacency list and track the degree of each node in the graph. Start from leaf nodes (excluding the capital) and process them using a queue with Breadth-First Search. Each leaf sends its representatives to its parent, requiring ceil(count / seats) cars for that edge. After processing, add its representative count to the parent and reduce the parent’s degree. When the parent becomes a leaf, push it into the queue. This bottom-up pruning approach effectively collapses the tree while accumulating the required fuel cost.
Recommended for interviews: The DFS aggregation approach is the most common solution. It directly models the tree structure and makes the representative merging logic clear. BFS leaf-pruning reaches the same result but is slightly less intuitive. Showing the DFS version first demonstrates strong understanding of tree traversal and subtree aggregation, which interviewers typically expect for this problem.
Approach 1: DFS to Compute Minimum Fuel Cost
Using Depth-First Search (DFS), we can traverse the tree from the capital city '0' and calculate the minimum fuel cost required to gather all representatives in the capital city. We need to propagate the number of representatives from child nodes towards the root (capital) while managing the representatives getting into available seats effectively.
def minimumFuelCost(roads, seats):
from collections import defaultdict
adjList = defaultdict(list)
visited = set()
def dfs(node):
visited.add(node)
total_rep = 1
for neighbor in adjList[node]:
if neighbor not in visited:
reps = dfs(neighbor)
nonlocal cost
cost += (reps + seats - 1) // seats
total_rep += reps
return total_rep
for a, b in roads:
adjList[a].append(b)
adjList[b].append(a)
cost = 0
dfs(0)
return cost
roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]]
seats = 2
print(minimumFuelCost(roads, seats))import java.util.*;
public class Solution {
static ArrayList<Integer>[] adjList;
static boolean[] visited;
private static int dfs(int node, int seats, long[] cost) {
visited[node] = true;
int representatives = 1;
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
int reps = dfs(neighbor, seats, cost);
cost[0] += (reps + seats - 1) / seats;
representatives += reps;
}
}
return representatives;
}
public static long minimumFuelCost(int[][] roads, int seats) {
int n = roads.length + 1;
adjList = new ArrayList[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}
for (int[] road : roads) {
adjList[road[0]].add(road[1]);
adjList[road[1]].add(road[0]);
}
long[] cost = new long[1];
dfs(0, seats, cost);
return cost[0];
}
public static void main(String[] args) {
int[][] roads = {{3,1},{3,2},{1,0},{0,4},{0,5},{4,6}};
int seats = 2;
System.out.println(minimumFuelCost(roads, seats));
}
}#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> adjList;
vector<bool> visited;
int dfs(int node, int seats, long long &cost) {
visited[node] = true;
int representatives = 1;
for (const int &neighbor : adjList[node]) {
if (!visited[neighbor]) {
int rep_count = dfs(neighbor, seats, cost);
cost += (rep_count + seats - 1) / seats;
representatives += rep_count;
}
}
return representatives;
}
long long minimumFuelCost(vector<vector<int>> &roads, int seats) {
int n = roads.size() + 1;
adjList = vector<vector<int>>(n);
visited = vector<bool>(n, false);
for (auto &road : roads) {
adjList[road[0]].push_back(road[1]);
adjList[road[1]].push_back(road[0]);
}
long long cost = 0;
dfs(0, seats, cost);
return cost;
}
int main() {
vector<vector<int>> roads = {{3,1},{3,2},{1,0},{0,4},{0,5},{4,6}};
int seats = 2;
cout << minimumFuelCost(roads, seats) << endl;
return 0;
}function minimumFuelCost(roads, seats) {
const adjList = new Map();
const visited = new Set();
function dfs(node) {
visited.add(node);
let representatives = 1;
for (let neighbor of (adjList.get(node) || [])) {
if (!visited.has(neighbor)) {
const reps = dfs(neighbor);
cost += Math.ceil(reps / seats);
representatives += reps;
}
}
return representatives;
}
for (const [a, b] of roads) {
if (!adjList.has(a)) adjList.set(a, []);
if (!adjList.has(b)) adjList.set(b, []);
adjList.get(a).push(b);
adjList.get(b).push(a);
}
let cost = 0;
dfs(0);
return cost;
}
const roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]];
const seats = 2;
console.log(minimumFuelCost(roads, seats));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CITIES 100000
// Adjacency list
int tree[MAX_CITIES][MAX_CITIES];
int child_count[MAX_CITIES];
int visited[MAX_CITIES];
int dfs(int node, int seats) {
visited[node] = 1;
int totalFuel = 0;
for (int i = 0; i < child_count[node]; ++i) {
int next = tree[node][i];
if (!visited[next]) {
int people = dfs(next, seats);
totalFuel += (people + seats - 1) / seats;
totalFuel += people; // Adding people to fuel calculation
}
}
return totalFuel + 1;
}
int minimumFuelCost(int roads[][2], int roadsSize, int seats) {
for (int i = 0; i < roadsSize; ++i) {
int a = roads[i][0];
int b = roads[i][1];
tree[a][child_count[a]++] = b;
tree[b][child_count[b]++] = a;
}
return dfs(0, seats) - 1; // Subtract 1 as node 0 doesn't use fuel
}
int main() {
int roads[5][2] = {{3,1},{3,2},{1,0},{0,4},{0,5},{4,6}};
int seats = 2;
printf("%d\n", minimumFuelCost(roads, 5, seats));
return 0;
}using System;
using System.Collections.Generic;
class Solution {
static List<int>[] adjList;
static bool[] visited;
static int Dfs(int node, int seats, ref long cost) {
visited[node] = true;
int representatives = 1;
foreach (int neighbor in adjList[node]) {
if (!visited[neighbor]) {
int reps = Dfs(neighbor, seats, ref cost);
cost += (reps + seats - 1) / seats;
representatives += reps;
}
}
return representatives;
}
public static long MinimumFuelCost(int[][] roads, int seats) {
int n = roads.Length + 1;
adjList = new List<int>[n];
visited = new bool[n];
for (int i = 0; i < n; ++i) adjList[i] = new List<int>();
foreach (var road in roads) {
adjList[road[0]].Add(road[1]);
adjList[road[1]].Add(road[0]);
}
long cost = 0;
Dfs(0, seats, ref cost);
return cost;
}
static void Main(string[] args) {
int[][] roads = new int[][] { new int[]{ 3,1}, new int[]{ 3,2}, new int[]{ 1,0}, new int[]{ 0,4}, new int[]{ 0,5}, new int[]{ 4,6}};
int seats = 2;
Console.WriteLine(MinimumFuelCost(roads, seats));
}
}This Python solution uses a DFS approach to traverse a graph from the capital node and compute the cost of fuel based on representatives. Recursion effectively manages graph traversal while non-local values track consumption of fuel according to available seats in the car.
Time Complexity: O(n), considering each node is processed once.
Space Complexity: O(n), for adjacency list and recursive calls stack.
Approach 2: BFS to Compute Minimum Fuel Cost
By utilizing Breadth-First Search (BFS), we can tackle this problem iteratively, processing nodes level by level from the capital outward. Track the representatives as they move towards the capital and the fuel cost incrementally.
from collections import defaultdict, deque
def minimumFuelCost(roads, seats):
adj = defaultdict(list)
for u, v in roads:
adj[u].append(v)
adj[v].append(u)
visited = set()
queue = deque([(0, 0)]) # (node, representatives)
visited.add(0)
cost = 0
while queue:
node, reps = queue.popleft()
max_reps = reps + 1
nodeFuel = (max_reps + seats - 1) // seats
cost += nodeFuel
for neigh in adj[node]:
if neigh not in visited:
visited.add(neigh)
queue.append((neigh, max_reps))
return cost
roads = [[0,1], [0,2], [0,3]]
seats = 5
print(minimumFuelCost(roads, seats))import java.util.*;
public class Solution {
public static long minimumFuelCost(int[][] roads, int seats) {
int n = roads.length + 1;
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < n; i++) adjList.add(new ArrayList<>());
for (int[] road : roads) {
adjList.get(road[0]).add(road[1]);
adjList.get(road[1]).add(road[0]);
}
boolean[] visited = new boolean[n];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
visited[0] = true;
long cost = 0;
while (!queue.isEmpty()) {
int[] top = queue.poll();
int node = top[0], reps = top[1];
int max_reps = reps + 1;
long nodeFuel = (max_reps + seats - 1) / seats;
cost += nodeFuel;
for (int neighbor : adjList.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.offer(new int[]{neighbor, max_reps});
}
}
}
return cost;
}
public static void main(String[] args) {
int[][] roads = {{0,1}, {0,2}, {0,3}};
int seats = 5;
System.out.println(minimumFuelCost(roads, seats));
}
}#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int minimumFuelCost(vector<vector<int>> &roads, int seats) {
int n = roads.size() + 1;
vector<vector<int>> adj(n);
for (auto &road : roads) {
adj[road[0]].push_back(road[1]);
adj[road[1]].push_back(road[0]);
}
vector<bool> visited(n, false);
queue<pair<int, int>> q;
q.push({0, 0});
visited[0] = true;
long long cost = 0;
while (!q.empty()) {
auto [node, reps] = q.front(); q.pop();
int max_reps = reps + 1;
long long fuel_for_node = (max_reps + seats - 1) / seats;
cost += fuel_for_node;
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push({neighbor, max_reps});
}
}
}
return cost;
}
int main() {
vector<vector<int>> roads = {{0,1}, {0,2}, {0,3}};
int seats = 5;
cout << minimumFuelCost(roads, seats) << endl;
return 0;
}function minimumFuelCost(roads, seats) {
const adjList = new Map();
for (const [a, b] of roads) {
if (!adjList.has(a)) adjList.set(a, []);
if (!adjList.has(b)) adjList.set(b, []);
adjList.get(a).push(b);
adjList.get(b).push(a);
}
const visited = new Set(), queue = [[0, 0]];
visited.add(0);
let cost = 0;
while (queue.length) {
const [node, reps] = queue.shift();
const max_reps = reps + 1;
const nodeFuel = Math.ceil(max_reps / seats);
cost += nodeFuel;
for (let neighbor of (adjList.get(node) || [])) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push([neighbor, max_reps]);
}
}
}
return cost;
}
const roads = [[0,1], [0,2], [0,3]];
const seats = 5;
console.log(minimumFuelCost(roads, seats));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 100000
typedef struct {
int node;
int reps;
} QueueItem;
QueueItem queue[MAX];
int front = 0, rear = 0;
void enqueue(int node, int reps) {
queue[rear++] = (QueueItem) {node, reps};
}
QueueItem dequeue() {
return queue[front++];
}
bool isEmpty() {
return front == rear;
}
int bfs(int graph[MAX][MAX], int* nodeCount, int seats, int n) {
bool visited[MAX] = {false};
int cost = 0;
enqueue(0, 0);
while (!isEmpty()) {
QueueItem item = dequeue();
int node = item.node, reps = item.reps;
visited[node] = true;
int max_reps = reps + 1;
for (int i = 0; i < nodeCount[node]; ++i) {
int next = graph[node][i];
if (!visited[next]) {
enqueue(next, max_reps);
cost += (max_reps + seats - 1) / seats;
}
}
}
return cost;
}
int main() {
int roads[][2] = {{0,1},{0,2},{0,3}};
int graph[MAX][MAX], nodeCount[MAX] = {0};
int roadsCount = sizeof(roads) / sizeof(roads[0]);
for (int i = 0; i < roadsCount; ++i) {
int a = roads[i][0], b = roads[i][1];
graph[a][nodeCount[a]++] = b;
graph[b][nodeCount[b]++] = a;
}
int seats = 5;
printf("%d\n", bfs(graph, nodeCount, seats, roadsCount + 1));
return 0;
}using System;
using System.Collections.Generic;
class Solution {
public static long MinimumFuelCost(int[][] roads, int seats) {
int n = roads.Length + 1;
List<int>[] adjList = new List<int>[n];
for (int i = 0; i < n; ++i) adjList[i] = new List<int>();
foreach (var road in roads) {
adjList[road[0]].Add(road[1]);
adjList[road[1]].Add(road[0]);
}
bool[] visited = new bool[n];
Queue<(int node, int reps)> q = new Queue<(int, int)>();
q.Enqueue((0, 0));
visited[0] = true;
long cost = 0;
while (q.Count > 0) {
var (node, reps) = q.Dequeue();
int max_reps = reps + 1;
long nodeFuel = (max_reps + seats - 1) / seats;
cost += nodeFuel;
foreach (int neighbor in adjList[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.Enqueue((neighbor, max_reps));
}
}
}
return cost;
}
static void Main() {
int[][] roads = { new int[]{0,1}, new int[]{0,2}, new int[]{0,3} };
int seats = 5;
Console.WriteLine(MinimumFuelCost(roads, seats));
}
}The Python solution constructs an adjacency list and uses a queue for BFS traversal, ensuring we're adding necessary roles to a full potential delegation. Consequently, each BFS iteration accounts for the fuel needed by constraining nodes via BFS into a specific directional queue.
Time Complexity: O(n), each city node will be tackled individually.
Space Complexity: O(n), owing to queue demand and adjacency mapping.
Approach 3: Greedy + DFS
According to the problem description, we can find that all cars will only drive towards the capital (node 0).
Suppose there is a node a, its next node is b, and node a needs to pass through node b to reach the capital. In order to make the vehicles (fuel consumption) of node a as small as possible, we should greedily let the vehicles of the child nodes of node a converge to node a first, and then distribute the vehicles according to the number of seats seats. The minimum number of vehicles (fuel consumption) needed to reach node b is \lceil \frac{sz}{seats} \rceil. Where sz represents the number of nodes in the subtree with node a as the root.
We start a depth-first search from node 0, using a variable sz to count the number of nodes in the subtree with the current node as the root. Initially, sz = 1, representing the current node itself. Then we traverse all the child nodes of the current node. For each child node b, we recursively calculate the number of nodes t in the subtree with b as the root, and add t to sz, and then we add \lceil \frac{t}{seats} \rceil to the answer. Finally, return sz.
The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes.
function minimumFuelCost(roads: number[][], seats: number): number {
const n = roads.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of roads) {
g[a].push(b);
g[b].push(a);
}
let ans = 0;
const dfs = (a: number, fa: number): number => {
let sz = 1;
for (const b of g[a]) {
if (b !== fa) {
const t = dfs(b, a);
ans += Math.ceil(t / seats);
sz += t;
}
}
return sz;
};
dfs(0, -1);
return ans;
}func minimumFuelCost(roads [][]int, seats int) (ans int64) {
n := len(roads) + 1
g := make([][]int, n)
for _, e := range roads {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
var dfs func(int, int) int
dfs = func(a, fa int) int {
sz := 1
for _, b := range g[a] {
if b != fa {
t := dfs(b, a)
ans += int64((t + seats - 1) / seats)
sz += t
}
}
return sz
}
dfs(0, -1)
return
}impl Solution {
pub fn minimum_fuel_cost(roads: Vec<Vec<i32>>, seats: i32) -> i64 {
let n = roads.len() + 1;
let mut g: Vec<Vec<usize>> = vec![vec![]; n];
for road in roads.iter() {
let a = road[0] as usize;
let b = road[1] as usize;
g[a].push(b);
g[b].push(a);
}
let mut ans = 0;
fn dfs(a: usize, fa: i32, g: &Vec<Vec<usize>>, ans: &mut i64, seats: i32) -> i32 {
let mut sz = 1;
for &b in g[a].iter() {
if (b as i32) != fa {
let t = dfs(b, a as i32, g, ans, seats);
*ans += ((t + seats - 1) / seats) as i64;
sz += t;
}
}
sz
}
dfs(0, -1, &g, &mut ans, seats);
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| DFS to Compute Minimum Fuel Cost | Time Complexity: O(n), considering each node is processed once. |
| BFS to Compute Minimum Fuel Cost | Time Complexity: O(n), each city node will be tackled individually. |
| Greedy + DFS | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| DFS Subtree Aggregation | O(n) | O(n) | Most intuitive for tree problems; directly aggregates representatives from children |
| BFS Leaf Pruning | O(n) | O(n) | Useful when processing trees bottom-up using queue and node degrees |
Frequently asked questions
Is Minimum Fuel Cost to Report to the Capital easy or hard?
The problem is classified as Medium on LeetCode. The graph structure is straightforward, but the challenge is recognizing that representatives can merge along the tree and that fuel cost should be calculated per edge using subtree counts.
Minimum Fuel Cost to Report to the Capital Python/Java solution
Most implementations build an adjacency list and run DFS from the capital. During traversal, each recursive call returns the number of representatives in that subtree. The algorithm calculates required cars using ceiling division and accumulates fuel cost. The same logic works in Python, Java, C++, C#, and JavaScript.
How to solve Minimum Fuel Cost to Report to the Capital in O(n)?
Model the roads as a tree rooted at city 0. Perform a DFS to count representatives in each subtree. When returning from a child node, compute the cars needed with ceil(subtree_representatives / seats) and add that to the fuel total. This bottom-up aggregation ensures representatives share cars as early as possible, giving the optimal O(n) solution.
What is the best approach for Minimum Fuel Cost to Report to the Capital?
The DFS subtree aggregation approach is typically considered the best solution. Traverse the tree from the capital and compute how many representatives exist in each subtree. For every edge to the parent, calculate the number of cars required using ceil(representatives / seats). This approach runs in O(n) time and O(n) space and cleanly models how representatives merge while moving toward the capital.
Is Minimum Fuel Cost to Report to the Capital asked at Google/Amazon/Meta?
Tree aggregation and graph traversal problems like this frequently appear in interviews at companies such as Amazon, Google, and Meta. The problem tests understanding of tree structures, DFS traversal, and resource aggregation across graph edges.
What data structure is used in Minimum Fuel Cost to Report to the Capital?
The solution primarily uses an adjacency list to represent the tree. DFS uses recursion and subtree counts, while the BFS alternative uses a queue and node degree tracking to process leaf nodes first.
What is the time complexity of Minimum Fuel Cost to Report to the Capital?
The optimal solution runs in O(n) time because each city and road in the tree is processed once. Both DFS and BFS approaches build an adjacency list and traverse the tree a single time. Space complexity is O(n) for storing the graph and recursion stack or queue.
