Problem Walkthrough

Gas Station LeetCode 134 Deep Dive

Single-pass greedy that tracks running tank balance and total surplus to pinpoint the unique valid starting station in one sweep.

9 min read|

Gas Station

LeetCode 134 Deep Dive

Problem Overview

LeetCode 134 Gas Station presents a circular route with n stations. At each station i you can collect gas[i] units of fuel, and it costs cost[i] units of fuel to travel from station i to station i+1. The final station connects back to station 0, completing the loop.

Your task: find the index of the starting station from which you can complete the full circular route without your fuel tank ever going negative. If no such starting point exists, return -1. The problem guarantees at most one valid answer.

This is a classic greedy problem that trips up candidates who reach for simulation or brute force. The elegant O(n) solution emerges once you see how local deficits and global surplus interact.

  • gas[i] = fuel gained at station i
  • cost[i] = fuel consumed driving from station i to station i+1
  • Tank starts at 0 and must never drop below 0
  • Route is circular: station n-1 connects back to station 0
  • Return the starting index, or -1 if the circuit is impossible

One-Pass Greedy Insight

The key observation is that if the total gas across all stations is at least equal to the total cost, a solution is guaranteed to exist — and it will be unique. This means you can solve existence and identification in the same pass.

Track a running tank as you iterate through every station. When the tank drops below zero at station j, you know that neither the current candidate start nor any station between the original start and j can reach j. Reset the candidate start to j+1 and reset the tank to zero.

After completing the loop, if totalGas >= totalCost, the last candidate start you settled on is the answer. Otherwise return -1. The entire algorithm runs in O(n) time with O(1) extra space.

💡

Greedy Insight

If you cannot reach station j starting from station i, you also cannot reach j starting from any station between i and j — because those intermediate starts have less accumulated surplus than i did. Skip directly to j+1 as the new candidate.

Algorithm Step by Step

The algorithm uses four variables: totalGas, totalCost, tank, and start. All are initialised to zero. A single for loop processes every station, updating all four values.

After the loop, a single conditional determines the answer: if totalGas >= totalCost the circuit is completable and start is the answer; otherwise return -1. No second pass, no nested loops, no auxiliary data structures.

Because the problem guarantees at most one valid start, the greedy candidate accumulated during the sweep is provably correct whenever a solution exists.

  1. 1Initialize: totalGas = 0, totalCost = 0, tank = 0, start = 0
  2. 2For each station i from 0 to n-1:
  3. 3 tank += gas[i] - cost[i]
  4. 4 totalGas += gas[i]
  5. 5 totalCost += cost[i]
  6. 6 If tank < 0: set start = i + 1 and tank = 0
  7. 7After loop: return totalGas >= totalCost ? start : -1

Why This Finds the Correct Start

Every station before the most recent reset point caused the tank to go negative when reached from some earlier candidate. That means they are all provably invalid as starting points. The reset point j+1 is the earliest station where the cumulative net gain from j+1 onward stays non-negative throughout the remaining route.

Formally, the greedy start is the station where the suffix sum of (gas[i] - cost[i]) is maximized. If the total surplus is non-negative, this suffix must be large enough to absorb the entire deficit accumulated in the prefix before it.

This is not just a heuristic — it is a guarantee. The uniqueness property of the problem means there is exactly one station with this property whenever a solution exists, and the greedy pass finds it without ever backtracking.

ℹ️

The Proof

totalSurplus >= 0 means enough gas exists to complete the circuit globally. The greedy start maximizes the running minimum of the tank, ensuring the tank never dips negative for the entire loop from that point. The prefix deficit is absorbed by the suffix surplus.

Walk-Through Example

Take gas = [1,2,3,4,5] and cost = [3,4,5,1,2]. Total gas = 15, total cost = 15. They are equal, so a solution is guaranteed. Now trace the greedy sweep.

At station 0: tank = 1-3 = -2 (negative). Reset start=1, tank=0. At station 1: tank = 2-4 = -2 (negative). Reset start=2, tank=0. At station 2: tank = 3-5 = -2 (negative). Reset start=3, tank=0.

From station 3 onward the tank stays non-negative: station 3 gives 4-1=3; station 4 gives 3+(5-2)=6; wrapping to station 0 gives 6+(1-3)=4; station 1 gives 4+(2-4)=2; station 2 gives 2+(3-5)=0. Tank never went negative. Answer: start = 3.

  1. 1Station 0: net = 1-3 = -2 → tank < 0 → reset start=1, tank=0
  2. 2Station 1: net = 2-4 = -2 → tank < 0 → reset start=2, tank=0
  3. 3Station 2: net = 3-5 = -2 → tank < 0 → reset start=3, tank=0
  4. 4Station 3: tank = 0 + (4-1) = 3
  5. 5Station 4: tank = 3 + (5-2) = 6
  6. 6totalGas (15) >= totalCost (15) → return start = 3

Code Walkthrough — Python and Java

In Python the solution is a single for loop: iterate i from 0 to n-1, update tank += gas[i] - cost[i], update totalGas and totalCost, and if tank < 0 reset start = i+1 and tank = 0. Return start if totalGas >= totalCost else -1. Time complexity O(n), space O(1).

In Java the structure is identical: a for loop with the same four assignments and a single conditional reset. The return statement mirrors the Python version. Both implementations are around 10 lines of code with no imports beyond basic I/O.

The elegance of this solution is that it collapses what might feel like a two-pass problem into one. The global feasibility check (totalGas vs totalCost) and the local candidate identification (tracking tank resets) happen simultaneously in the same loop.

⚠️

Avoid the Naive Approach

Do not try all n starting stations and simulate the full circuit from each — that is O(n^2) and will time out on large inputs. The greedy skip property is the insight that makes O(n) possible: a failed reach to station j eliminates all candidates up to j in one step.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now