Total Distance Traveled solution and explanation
9 more videos on this problem
Leetcode | 2739. Total Distance Traveled | Easy | Java SolutionDeveloper Docs · 3:53 · 914 views
Leetcode Weekly contest 350 - Easy - Total Distance TraveledPrakhar Agrawal · 7:48 · 751 views
2739. Total Distance Traveled (Leetcode Easy)Programming Live with Larry · 4:09 · 370 views
Total Distance Traveled | Leetcode 2739 | Weekly 350Tech Courses · 3:38 · 355 views
Leetcode 2739 Total Distance TraveledTech Diet · 4:52 · 171 views
Leetcode 2739 || Total Distance Traveled || Leetcode Weekly Easy || cppKomal Pal · 12:51 · 115 views
Unleash Your Coding Speed! Fastest Python Solution for 'Total Distance Traveled' | LeetCode 2739vanAmsen · 4:25 · 71 views
Total Distance Traveled | Leetcode 2739 | Approach + Code with explanation.Pirai's Academy · 9:45 · 66 views
One Coding Problem 7 Languages: Ultimate Coding Challenge - LeetCode 2739 Total Distance TraveledvanAmsen · 15:14 · 56 views
LeetCode 2739: Total Distance Traveled | Solution in JavaTech Traverse · 11:52 · 35 views
The problem
A truck has two fuel tanks. You are given two integers, mainTank representing the fuel present in the main tank in liters and additionalTank representing the fuel present in the additional tank in liters.
The truck has a mileage of 10 km per liter. Whenever 5 liters of fuel get used up in the main tank, if the additional tank has at least 1 liters of fuel, 1 liters of fuel will be transferred from the additional tank to the main tank.
Return the maximum distance which can be traveled.
Note: Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.
Example 1:
Input: mainTank = 5, additionalTank = 10 Output: 60 Explanation: After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km. After spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty. Total distance traveled is 60km.
Example 2:
Input: mainTank = 1, additionalTank = 2 Output: 10 Explanation: After spending 1 litre of fuel, the main tank becomes empty. Total distance traveled is 10km.
Constraints:
1 <= mainTank, additionalTank <= 100
Approach overview
Problem Overview: You are given two integers: mainTank and additionalTank. A truck consumes 1 liter of fuel for every 10 km traveled. Each time the truck uses 5 liters from the main tank, you can transfer 1 liter from the additional tank to the main tank (if available). The goal is to compute the total distance the truck can travel.
Approach 1: Simulation Approach (Time: O(n), Space: O(1))
This method follows the exact process described in the problem using simulation. You repeatedly consume fuel from the main tank while tracking how many liters have been used. After every 5 liters consumed, check whether the additional tank still has fuel. If it does, transfer 1 liter to the main tank and continue driving. The loop continues until the main tank becomes empty. The final distance equals the total liters consumed multiplied by 10. This approach mirrors the real-world process step by step and is useful when verifying the mechanics of the rule or when constraints are small.
Approach 2: Direct Calculation Approach (Time: O(1), Space: O(1))
The fuel transfer rule reveals a mathematical pattern. For every 5 liters consumed from the main tank, you gain 1 extra liter from the additional tank. However, the last few liters may not complete another group of 5, so they do not trigger another transfer. The number of possible transfers is therefore (mainTank - 1) / 4 using integer division. This works because each transfer effectively increases usable fuel before the next group of five is completed. The actual number of transferred liters is limited by additionalTank, so the formula becomes extra = min(additionalTank, (mainTank - 1) // 4). The total usable fuel becomes mainTank + extra, and the final distance is that value multiplied by 10.
This approach relies on recognizing the repeating pattern rather than explicitly simulating each step. It uses simple math and constant-time arithmetic, which makes it significantly cleaner and faster.
Recommended for interviews: The direct calculation approach is usually what interviewers expect. Simulation demonstrates that you understand the mechanics of the rule, but recognizing the mathematical pattern and reducing the solution to O(1) time shows stronger problem-solving and optimization skills.
Approach 1: Simulation Approach
This approach involves simulating the consumption of fuel from the main tank and the transfer of fuel from the additional tank when the main tank consumes 5 liters. We continue this process until the fuel in the main tank is completely depleted and no more can be injected from the additional tank.
def total_distance(mainTank, additionalTank):
distance = 0
while mainTank > 0:
use = min(mainTank, 5)
distance += use * 10
mainTank -= use
if use == 5 and additionalTank > 0:
mainTank += 1
additionalTank -= 1
return distance
print("Total distance:", total_distance(5, 10), "km")public class Solution {
public static int totalDistance(int mainTank, int additionalTank) {
int distance = 0;
while (mainTank > 0) {
int use = Math.min(mainTank, 5);
distance += use * 10;
mainTank -= use;
if (use == 5 && additionalTank > 0) {
mainTank += 1;
additionalTank -= 1;
}
}
return distance;
}
public static void main(String[] args) {
int mainTank = 5, additionalTank = 10;
System.out.println("Total distance: " + totalDistance(mainTank, additionalTank) + " km");
}
}#include <iostream>
using namespace std;
int totalDistance(int mainTank, int additionalTank) {
int distance = 0;
while (mainTank > 0) {
int use = mainTank >= 5 ? 5 : mainTank;
distance += use * 10;
mainTank -= use;
if (use == 5 && additionalTank > 0) {
mainTank += 1;
additionalTank -= 1;
}
}
return distance;
}
int main() {
int mainTank = 5, additionalTank = 10;
cout << "Total distance: " << totalDistance(mainTank, additionalTank) << " km" << endl;
return 0;
}function totalDistance(mainTank, additionalTank) {
let distance = 0;
while (mainTank > 0) {
let use = Math.min(mainTank, 5);
distance += use * 10;
mainTank -= use;
if (use === 5 && additionalTank > 0) {
mainTank += 1;
additionalTank -= 1;
}
}
return distance;
}
console.log("Total distance:", totalDistance(5, 10), "km");#include <stdio.h>
int totalDistance(int mainTank, int additionalTank) {
int distance = 0;
while (mainTank > 0) {
int use = mainTank >= 5 ? 5 : mainTank;
distance += use * 10;
mainTank -= use;
if (use == 5 && additionalTank > 0) {
mainTank += 1;
additionalTank -= 1;
}
}
return distance;
}
int main() {
int mainTank = 5, additionalTank = 10;
printf("Total distance: %d km\n", totalDistance(mainTank, additionalTank));
return 0;
}using System;
class Program {
public static int TotalDistance(int mainTank, int additionalTank) {
int distance = 0;
while (mainTank > 0) {
int use = Math.Min(mainTank, 5);
distance += use * 10;
mainTank -= use;
if (use == 5 && additionalTank > 0) {
mainTank += 1;
additionalTank -= 1;
}
}
return distance;
}
static void Main() {
int mainTank = 5, additionalTank = 10;
Console.WriteLine("Total distance: " + TotalDistance(mainTank, additionalTank) + " km");
}
}This Python code calculates total distance traveled by iteratively consuming fuel in increments capped at 5 liters, while transferring fuel when conditions are met.
Time Complexity: O(mainTank).
Space Complexity: O(1).
Approach 2: Direct Calculation Approach
This approach calculates the maximum travelable distance directly using arithmetic by simulating potential transfers in a streamlined calculation. Instead of iterating, it computes the total number of 5-liter chunks that can be used, applying additional transfers one at a time as allowable by the additional tank.
def total_distance(mainTank, additionalTank):
total_distance = 0
while mainTank >= 5:
full_chunks = mainTank // 5
available_transfers = min(full_chunks, additionalTank)
total_distance += (mainTank + available_transfers) * 10
break
return total_distance
print("Total distance:", total_distance(5, 10), "km")public class Solution {
public static int totalDistance(int mainTank, int additionalTank) {
int totalDistance = 0;
while (mainTank >= 5) {
int fullChunks = mainTank / 5;
int availableTransfers = Math.min(fullChunks, additionalTank);
totalDistance += (mainTank + availableTransfers) * 10;
break;
}
return totalDistance;
}
public static void main(String[] args) {
int mainTank = 5, additionalTank = 10;
System.out.println("Total distance: " + totalDistance(mainTank, additionalTank) + " km");
}
}#include <iostream>
using namespace std;
int totalDistance(int mainTank, int additionalTank) {
int totalDistance = 0;
while (mainTank >= 5) {
int fullChunks = mainTank / 5;
int availableTransfers = fullChunks > additionalTank ? additionalTank : fullChunks;
totalDistance += (mainTank + availableTransfers) * 10;
break;
}
return totalDistance;
}
int main() {
int mainTank = 5, additionalTank = 10;
cout << "Total distance: " << totalDistance(mainTank, additionalTank) << " km" << endl;
return 0;
}function totalDistance(mainTank, additionalTank) {
let totalDistance = 0;
while (mainTank >= 5) {
let fullChunks = Math.floor(mainTank / 5);
let availableTransfers = Math.min(fullChunks, additionalTank);
totalDistance += (mainTank + availableTransfers) * 10;
break;
}
return totalDistance;
}
console.log("Total distance:", totalDistance(5, 10), "km");#include <stdio.h>
int totalDistance(int mainTank, int additionalTank) {
int totalDistance = 0;
while (mainTank >= 5) {
int fullChunks = mainTank / 5;
int availableTransfers = fullChunks > additionalTank ? additionalTank : fullChunks;
totalDistance += (mainTank + availableTransfers) * 10;
break; // Exit loop after computation
}
return totalDistance;
}
int main() {
int mainTank = 5, additionalTank = 10;
printf("Total distance: %d km\n", totalDistance(mainTank, additionalTank));
return 0;
}using System;
class Program {
public static int TotalDistance(int mainTank, int additionalTank) {
int totalDistance = 0;
while (mainTank >= 5) {
int fullChunks = mainTank / 5;
int availableTransfers = Math.Min(fullChunks, additionalTank);
totalDistance += (mainTank + availableTransfers) * 10;
break;
}
return totalDistance;
}
static void Main() {
int mainTank = 5, additionalTank = 10;
Console.WriteLine("Total distance: " + TotalDistance(mainTank, additionalTank) + " km");
}
}This Python solution computes the total travelable distance by considering how many complete 5-liter consumptions and simultaneous fuel injections from the additional tank are possible.
Time Complexity: O(1).
Space Complexity: O(1).
Approach 3: Simulation
We can simulate the process of the truck's movement. Each time, it consumes 1 liter of fuel from the main fuel tank and travels 10 kilometers. Whenever the fuel in the main fuel tank is consumed by 5 liters, if there is fuel in the auxiliary fuel tank, 1 liter of fuel is transferred from the auxiliary fuel tank to the main fuel tank. The simulation continues until the fuel in the main fuel tank is exhausted.
The time complexity is O(n + m), where n and m are the amounts of fuel in the main and auxiliary fuel tanks, respectively. The space complexity is O(1).
func distanceTraveled(mainTank int, additionalTank int) (ans int) {
cur := 0
for mainTank > 0 {
cur++
ans += 10
mainTank--
if cur%5 == 0 && additionalTank > 0 {
additionalTank--
mainTank++
}
}
return
}impl Solution {
pub fn distance_traveled(mut main_tank: i32, mut additional_tank: i32) -> i32 {
let mut cur = 0;
let mut ans = 0;
while main_tank > 0 {
cur += 1;
main_tank -= 1;
ans += 10;
if cur % 5 == 0 && additional_tank > 0 {
additional_tank -= 1;
main_tank += 1;
}
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Simulation Approach | Time Complexity: O(mainTank). |
| Direct Calculation Approach | Time Complexity: O(1). |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Simulation | O(n) | O(1) | Useful when implementing the process exactly as described or validating the transfer logic step-by-step |
| Direct Calculation (Math Formula) | O(1) | O(1) | Best choice for interviews and production code since the pattern allows constant-time computation |
Frequently asked questions
Is Total Distance Traveled easy or hard?
Total Distance Traveled is categorized as an Easy problem. The simulation version is straightforward, while the optimized solution requires recognizing a small mathematical pattern to achieve constant-time complexity.
How to solve Total Distance Traveled in O(1)?
Calculate the number of possible fuel transfers using integer division: (mainTank - 1) // 4. The actual number of extra liters is min(additionalTank, (mainTank - 1) // 4). Add this to mainTank to get total usable fuel, then multiply by 10 to get the total distance.
Total Distance Traveled Python or Java solution
Both Python and Java implementations are straightforward. The optimal solution calculates extra fuel transfers using min(additionalTank, (mainTank - 1) // 4), adds that to mainTank, and multiplies the result by 10 to get the total distance.
What is the best approach for Total Distance Traveled?
The best approach is the direct mathematical calculation. Instead of simulating fuel consumption step by step, compute how many times the truck can receive an extra liter using (mainTank - 1) // 4. The number of transfers is limited by additionalTank. This produces an O(1) time and O(1) space solution.
What data structure is used in Total Distance Traveled?
No special data structure is required. The problem relies mainly on arithmetic operations and simple counters. The two main techniques involved are simulation and mathematical pattern analysis.
What is the time complexity of Total Distance Traveled?
The optimal solution runs in O(1) time and O(1) space because it uses a constant number of arithmetic operations. A simulation approach that repeatedly consumes fuel can take O(n) time where n is the amount of fuel processed.
Is Total Distance Traveled asked at Google, Amazon, or Meta?
Problems like Total Distance Traveled commonly appear in coding interviews at large tech companies because they test pattern recognition, simulation logic, and simple mathematical optimization. While the exact problem may vary, the concept is typical of easy interview warm-up questions.
