Tensorum
LeetCode 134 · Jump / Reachability

Gas Station

LeetCode 134 · Medium · solution, intuition & step-by-step walkthrough

Reset the start after any negative running tank.

MediumArrayGreedy
30 msruntime · beats 39%
25.8 MBmemory · beats 65%
1approach
8accepted runs · last 1 Jun 2026

This is how I solved Gas Station (LeetCode 134), a medium problem from the Jump / Reachability pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

If total gas is less than total cost, no start works. Otherwise drive from a candidate start keeping a running tank; if the tank goes negative at i, no station between the start and i can work either, so restart from i + 1.

Approach

  1. 1

    Total check → −1 if impossible.

  2. 2

    Accumulate gas[i] − cost[i].

  3. 3

    Negative → start = i + 1, tank = 0.

  4. 4

    Return start.

How I solved it

Greedy single passPythonO(n) time · O(1) space
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(cost)>sum(gas):
            return -1
        i=0
        start=0
        effort = 0
        while i<len(gas):
            effort += gas[i]-cost[i]
            if effort<0:
                effort=0
                start=i+1
            i+=1
        return start
Loading the step-through…

Gas Station — FAQ

What is the intuition behind Gas Station?

If total gas is less than total cost, no start works. Otherwise drive from a candidate start keeping a running tank; if the tank goes negative at i, no station between the start and i can work either, so restart from i + 1.

How do you solve Gas Station (LeetCode 134)?

1. Total check → −1 if impossible. 2. Accumulate gas[i] − cost[i]. 3. Negative → start = i + 1, tank = 0. 4. Return start.

What is the time and space complexity of Gas Station?

Time: O(n). Space: O(1). (Accepted approach: Greedy single pass.)

What are common mistakes in Gas Station?

The total check is what guarantees the found start completes the loop.