Total Distance Traveled — LeetCode 2739 Python Solution

EasyMathSimulation
Problem
#2739
Reading time
2 min

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.

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.

Python solution

Python
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

MeasureComplexity
TimeO(n + m), where n and m are the amounts of fuel in the main and auxiliary fuel tanks, respectively
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2739. Total Distance Traveled is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2739. Total Distance Traveled?
LeetCode 2739. Total Distance Traveled is rated Easy on LeetCode.
What is the time complexity of LeetCode 2739. Total Distance Traveled?
The Python solution on this page runs in O(n + m), where n and m are the amounts of fuel in the main and auxiliary fuel tanks, respectively.
What is the space complexity of LeetCode 2739. Total Distance Traveled?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2739. Total Distance Traveled cover?
LeetCode 2739. Total Distance Traveled is tagged Math and Simulation 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.

Get Stealth Interview