Leetcode #2739: Total Distance Traveled
In this guide, we solve Leetcode #2739 Total Distance Traveled in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Math, Simulation
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
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.
Python Solution
class Solution:
def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
ans = cur = 0
while mainTank:
cur += 1
ans += 10
mainTank -= 1
if cur % 5 == 0 and additionalTank:
additionalTank -= 1
mainTank += 1
return ans
Complexity
The time complexity is , where and are the amounts of fuel in the main and auxiliary fuel tanks, respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.