DSA AnimatorDSA animations
Gas Station LC #134 Medium Greedy · Reset
Problem

There are n gas stations arranged in a circle. You are given two arrays gas and cost. At station i you collect gas[i] units of gas; it costs cost[i] to travel to station i+1. Starting with an empty tank, return the starting station index if you can complete the circuit once, otherwise return -1.

Example 1
Input: gas = [1,2,3,4,5]   cost = [3,4,5,1,2]
Output: 3
Explanation: Start at station 3: 4−1=3, +5−2=6, +1−3=4, +2−4=2, +3−5=0. Tank never goes negative.
Example 2
Input: gas = [2,3,4]   cost = [3,4,3]
Output: -1
Explanation: Total gas (9) < total cost (10). Impossible.
Constraints: n == gas.length == cost.length  |  1 ≤ n ≤ 10⁵  |  0 ≤ gas[i], cost[i] ≤ 10⁴
Try Examples
Custom:
Approach
Greedy Reset — Find the Valid Starting Station
If tank < 0 after any station, that start fails — try i+1. If total ≥ 0, a solution exists.
Station Circuit
start
Variables
Tank
0
Index i
—
diff
—
total
0
start
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
diff[i] = gas[i] - cost[i] (net gas at station i)
2
total += diff — tracks global feasibility across all stations
3
tank += diff — tracks journey from current start
4
If tank < 0: start = i + 1; tank = 0 — reset candidate
5
Return total ≥ 0 ? start : -1 — feasible only if net gas non-negative
Time
O(n)
Space
O(1)
Why Greedy Works

Two key observations: (1) If total ≥ 0, a valid start must exist — total gas is sufficient. (2) Whenever the running tank drops below zero after station i, none of the stations from the current start to i can be the answer (they'd all result in a negative tank sooner). So we safely skip to i+1. The last valid start candidate after the full scan is the answer.

How to solve Gas Station

LeetCode 134 · Medium · Greedy · Pattern: Greedy Reset

Why the obvious approach is slow

Simulating a trip from every station is O(n²). Two facts make it linear.

The key idea

First, if the total gas is less than the total cost, no start can work. Second, if the tank goes negative at station i, no station between the start and i can work either. So reset the start to i plus 1 and empty the tank.

Remember

A failure at i rules out every start before it. If the total is not negative, the last reset is the answer.

Run the animation above on your own input, or watch the 1:25 video explanation of Gas Station with a dry run and Java code.

More Greedy problems