#2477
Minimum Fuel Cost to Report to the Capital
MediumTreeDepth-First SearchBreadth-First SearchGraph TheoryDepth-First SearchTree TraversalGraph Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a depth-first search (DFS) to calculate the size of each subtree. By knowing how many representatives are in each subtree, we can efficiently calculate the minimum number of cars needed to transport them to the capital.
⚙️
Algorithm
4 steps- 1Step 1: Build a graph from the roads input.
- 2Step 2: Use DFS to calculate the size of each subtree rooted at each city.
- 3Step 3: For each subtree, calculate the number of cars needed based on the number of representatives and seats available.
- 4Step 4: Sum the total fuel costs for all representatives to reach the capital.
solution.py32 lines
1# Full working Python code
2from collections import defaultdict
3
4def minFuelCost(roads, seats):
5 graph = defaultdict(list)
6 for a, b in roads:
7 graph[a].append(b)
8 graph[b].append(a)
9
10 def dfs(node, parent):
11 total_representatives = 1 # Count this node as a representative
12 for neighbor in graph[node]:
13 if neighbor != parent:
14 total_representatives += dfs(neighbor, node)
15 return total_representatives
16
17 total_fuel = 0
18 def dfsFuel(node, parent):
19 nonlocal total_fuel
20 total_representatives = 1 # Count this node as a representative
21 for neighbor in graph[node]:
22 if neighbor != parent:
23 reps = dfsFuel(neighbor, node)
24 total_fuel += (reps + seats - 1) // seats
25 total_representatives += reps
26 return total_representatives
27
28 dfsFuel(0, -1)
29 return total_fuel
30
31# Example usage:
32print(minFuelCost([[0,1],[0,2],[0,3]], 5)) # Output: 3ℹ
Complexity note: The time complexity is O(n) because we traverse each node once during the DFS. The space complexity is O(n) due to the storage of the graph and the recursion stack.
- 1Understanding the tree structure helps in visualizing the representatives' paths to the capital.
- 2Calculating the size of each subtree allows for efficient car pooling.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.