← Back to DSA Animator
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.