15% off all plans & roadmaps Use code
See plansGas Station
- LeetCode 134
- Medium
- Greedy Patterns
- Gas Station Circuit
Updated
TL;DR: Find the one station where a full clockwise lap works, or return -1. Track the running fuel balance, restart the candidate whenever it goes negative, and check that total gas covers total cost.
Problem
There are n gas stations on a circular route. Station i holds gas[i] units of gas.
Your car has an unlimited tank. Driving from station i to station i + 1 costs cost[i] units of gas. You start at one station with an empty tank.
Given the arrays gas and cost, return the index of the station where you can start and drive once around the circuit clockwise. If no such station exists, return -1. If a solution exists, it is guaranteed to be unique.
Example 1
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3 Explanation: Start at station 3 and fill up with 4 units. The tank is 4. Drive to station 4: 4 - 1 + 5 = 8. Drive to station 0: 8 - 2 + 1 = 7. Drive to station 1: 7 - 3 + 2 = 6. Drive to station 2: 6 - 4 + 3 = 5. Drive back to station 3, which costs 5, and the tank holds exactly enough. Return 3.
Example 2
Input: gas = [2,3,4], cost = [3,4,3] Output: -1 Explanation: You cannot start at station 0 or 1, because you cannot reach the next station. Start at station 2 and fill up with 4 units. Drive to station 0: 4 - 3 + 2 = 3. Drive to station 1: 3 - 3 + 3 = 3. Returning to station 2 costs 4 but you hold only 3. No starting station works.
Constraints
n == gas.length == cost.length1 <= n <= 10^50 <= gas[i], cost[i] <= 10^4- The input is generated so that the answer is unique.
Constraints that matter
- n up to 10^5 rules out O(n^2). Simulating a full lap from every station means about 10^10 steps in the worst case, which times out.
- The answer is unique when it exists, so the first valid start you find is the only one. You never need to compare candidates.
- Values are at most 10^4 and n is at most 10^5, so any running sum stays within 10^9 in magnitude. A 32-bit int is safe in Java, C++ and C#.
- gas[i] and cost[i] can be 0, so a station can give nothing or cost nothing. A tank of exactly 0 is still allowed, so test
< 0and never<= 0. - n can be 1. A single station works exactly when gas[0] >= cost[0], and the loops must handle that without special code.
Hints
Hint 1
This is a greedy problem built on prefix sums.
Hint 2
Treat every station as a possible start.
Solution
Intuition
This is a greedy problem built on prefix sums. Define the net gain at station i as gas[i] - cost[i]. The car survives a leg as long as the running sum of net gains never goes below zero.
Picture a single fuel gauge on one long road trip. The gauge is the running balance, and when it dips below zero you move the start to the next stop and reset the gauge to empty.
Two facts do all the work. First, if the total net gain over the whole circle is negative, no start can work, because a full lap consumes more than it collects. Second, if you start at s and the tank first goes negative at station i, then no station between s and i can be a good start either.
The second fact is the key. To reach any station k between s and i, you arrived with a tank of at least 0. Starting fresh at k gives you exactly 0, which is never more than what you had. If the longer trip from s failed at i, the trip from k fails at i or earlier. So you can skip every station up to i and try i + 1.
That turns n separate simulations into one pass. You keep one candidate start and one running balance. When the balance goes negative, you drop the candidate and move it forward. At the end, the total tells you whether the surviving candidate also survives the wrap-around.
Worked example
Input: gas = [2, 3, 4], cost = [3, 4, 3] Output: -1 Explanation: The net gain per station (gas minus cost) is [-1, -1, 1]. These add up to -1, so the whole circuit holds less gas than it costs. No starting station can finish the lap.
Approach 1: Brute force
Treat every station as a possible start. For each one, simulate the lap: add gas[j] - cost[j] at each station, wrapping with modulo, and stop as soon as the tank goes below zero.
This is correct because it mirrors the problem exactly. It is slow because the simulations share nothing.
Steps
- Loop
startfrom 0 to n - 1. - Set
tank = 0for this start. - Loop
stepfrom 0 to n - 1 and computej = (start + step) % n. - Add
gas[j] - cost[j]totank. - If
tank < 0, abandon this start and move to the next one. - If all n steps finish with a non-negative tank, return
start. - If no start survives, return -1.
Dry run
Net gains are [-1, -1, 1].
- Start 0: after station 0 the tank is -1. Fail.
- Start 1: after station 1 the tank is -1. Fail.
- Start 2: after station 2 the tank is 1. After station 0 it is 0. After station 1 it is -1. Fail.
No start survives, so the answer is -1.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Here n is the number of stations. The outer loop runs n times and the inner loop runs at most n times each, so the worst case is n * n steps. With n = 10^5 that is about 10^10 steps, too many for the time limit. The code keeps only a start index, a step index and a tank, so space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
for start in range(n):
tank = 0
ok = True
for step in range(n):
j = (start + step) % n
tank += gas[j] - cost[j]
if tank < 0:
ok = False
break
if ok:
return start
return -1JavaTested in our runner
import java.util.*;
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
for (int start = 0; start < n; start++) {
int tank = 0;
boolean ok = true;
for (int step = 0; step < n; step++) {
int j = (start + step) % n;
tank += gas[j] - cost[j];
if (tank < 0) {
ok = false;
break;
}
}
if (ok) return start;
}
return -1;
}
}C++Tested in our runner
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
for (int start = 0; start < n; start++) {
int tank = 0;
bool ok = true;
for (int step = 0; step < n; step++) {
int j = (start + step) % n;
tank += gas[j] - cost[j];
if (tank < 0) {
ok = false;
break;
}
}
if (ok) return start;
}
return -1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function(gas, cost) {
const n = gas.length;
for (let start = 0; start < n; start++) {
let tank = 0;
let ok = true;
for (let step = 0; step < n; step++) {
const j = (start + step) % n;
tank += gas[j] - cost[j];
if (tank < 0) {
ok = false;
break;
}
}
if (ok) return start;
}
return -1;
};GoTested in our runner
func canCompleteCircuit(gas []int, cost []int) int {
n := len(gas)
for start := 0; start < n; start++ {
tank := 0
ok := true
for step := 0; step < n; step++ {
j := (start + step) % n
tank += gas[j] - cost[j]
if tank < 0 {
ok = false
break
}
}
if ok {
return start
}
}
return -1
}C#Tested in our runner
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.Length;
for (int start = 0; start < n; start++) {
int tank = 0;
bool ok = true;
for (int step = 0; step < n; step++) {
int j = (start + step) % n;
tank += gas[j] - cost[j];
if (tank < 0) {
ok = false;
break;
}
}
if (ok) return start;
}
return -1;
}
}Approach 2: Two pointers on a growing window
What's slow: brute force restarts from scratch for each start, even though neighbouring starts cover almost the same stations. Each new start throws away all the fuel arithmetic from the last one.
The insight that fixes it: keep one window of consecutive stations and its tank balance. Begin with the window holding only the last station. If the balance is non-negative, extend the window forward by one station at the end pointer.
If the balance is negative, the start is wrong. Extend the window backward by one station at the start pointer, which adds a new gain at the front. Each step adds exactly one station to the window.
Steps
- Set
start = n - 1andend = 0. Settank = gas[start] - cost[start]. - Loop while
start > end. The window then holdsn - 1 - end + 1plusendstations, fewer than n. - If
tank >= 0, add the net gain atendtotankand doend += 1. - Otherwise do
start -= 1and add the net gain at the newstarttotank. - When the pointers meet, the window covers all n stations once, so
tankequals the total net gain. - Return
startiftank >= 0, else return -1.
Dry run
Net gains are [-1, -1, 1]. Start with start = 2, end = 0, tank = 1.
tank = 1 >= 0, so add the gain at index 0: tank becomes 0,end = 1.tank = 0 >= 0, so add the gain at index 1: tank becomes -1,end = 2.- Now
start == end, so the loop stops. The window covers every station. tank = -1 < 0, so return -1.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the number of stations. The window starts with one station and each loop iteration adds one more, either at the front or the back. The loop stops when the pointers meet, so it runs at most n - 1 times. Only four integers are stored.
PythonTested in our runner
from typing import List, Optional
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
start, end = n - 1, 0
tank = gas[start] - cost[start]
while start > end:
if tank >= 0:
# window is healthy, extend it forward
tank += gas[end] - cost[end]
end += 1
else:
# window is short of fuel, extend it backward
start -= 1
tank += gas[start] - cost[start]
if tank < 0:
return -1
# prefer the smallest valid index: j < start is valid iff P[j] <= min(P[j+1..start])
best = start
rel = 0 # P[j] - P[start], tracked while walking back
m = 0 # min of P[k]-P[start] for k in (j, start]
for j in range(start - 1, -1, -1):
rel -= gas[j] - cost[j]
if rel <= m:
best = j
m = rel
return bestJavaTested in our runner
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int start = n - 1, end = 0;
int tank = gas[start] - cost[start];
// grow the window until it covers all stations
while (start > end) {
if (tank >= 0) {
tank += gas[end] - cost[end];
end++;
} else {
start--;
tank += gas[start] - cost[start];
}
}
if (tank < 0) return -1;
// pick the smallest valid start: prefix sums P, total T
long[] p = new long[n];
long s = 0;
for (int i = 0; i < n; i++) {
s += gas[i] - cost[i];
p[i] = s;
}
long t = s;
long[] suf = new long[n + 1];
suf[n] = Long.MAX_VALUE;
for (int i = n - 1; i >= 0; i--) suf[i] = Math.min(suf[i + 1], p[i]);
long pre = Long.MAX_VALUE; // min of p[i] for i < j
for (int j = 0; j < n; j++) {
long base = j == 0 ? 0 : p[j - 1];
boolean ok = suf[j] - base >= 0;
if (ok && j > 0) ok = t + pre - base >= 0;
if (ok) return j;
pre = Math.min(pre, p[j]);
}
return start;
}
}C++Tested in our runner
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int start = n - 1, end = 0;
int tank = gas[start] - cost[start];
// grow the window until it covers all stations
while (start > end) {
if (tank >= 0) {
tank += gas[end] - cost[end];
end++;
} else {
start--;
tank += gas[start] - cost[start];
}
}
if (tank < 0) return -1;
// a solution exists; pick the smallest valid start (ties)
int cur = 0, res = 0;
for (int i = 0; i < n; i++) {
cur += gas[i] - cost[i];
if (cur < 0) {
cur = 0;
res = i + 1;
}
}
return res;
}
};JavaScriptTested in our runner
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function(gas, cost) {
const n = gas.length;
let start = n - 1, end = 0;
let tank = gas[start] - cost[start];
// grow the window until it covers all stations
while (start > end) {
if (tank >= 0) {
tank += gas[end] - cost[end];
end++;
} else {
start--;
tank += gas[start] - cost[start];
}
}
if (tank < 0) return -1;
// pick the smallest valid start (answers can tie): restart after each failure
let best = 0, cur = 0;
for (let i = 0; i < n; i++) {
cur += gas[i] - cost[i];
if (cur < 0) {
best = i + 1;
cur = 0;
}
}
return best;
};GoTested in our runner
func canCompleteCircuit(gas []int, cost []int) int {
n := len(gas)
start, end := n-1, 0
tank := gas[start] - cost[start]
// grow the window until it covers all stations
for start > end {
if tank >= 0 {
tank += gas[end] - cost[end]
end++
} else {
start--
tank += gas[start] - cost[start]
}
}
if tank < 0 {
return -1
}
// pick the smallest valid start: first index with minimal prefix sum
best, bestP, p := 0, 0, 0
for i := 0; i < n; i++ {
if p < bestP {
bestP = p
best = i
}
p += gas[i] - cost[i]
}
return best
}
Solution pattern
Gas Station Circuit
Part of Greedy Patterns
Approach 3: One-pass greedyOptimalGas Station Circuit
What's slow: the two-pointer window still makes you reason about growing in two directions, and it is easy to get the pointer moves wrong. Brute force also repeats work after every failure.
The insight that fixes it: when a run starting at s fails at i, every station from s to i is ruled out, so jump the candidate to i + 1 and reset the run balance. Walk the array once, keep a running total of all net gains, and keep a run balance that resets on failure. At the end, a negative total means -1. Otherwise the last candidate is the answer.
Steps
- Set
total = 0,current = 0andstart = 0. - For each index
i, computediff = gas[i] - cost[i]. - Add
diffto bothtotalandcurrent. - If
current < 0, setstart = i + 1andcurrent = 0. - After the loop, return -1 if
total < 0. - Otherwise return
start.
Dry run
Trace on gas = [2, 3, 4], cost = [3, 4, 3].
| i | diff | total | current before reset | start |
|---|---|---|---|---|
| 0 | -1 | -1 | -1, below 0, reset to 0 | 1 |
| 1 | -1 | -2 | -1, below 0, reset to 0 | 2 |
| 2 | 1 | -1 | 1, stays | 2 |
The loop ends with total = -1, which is below 0, so the answer is -1.
On Example 1 (gas = [1,2,3,4,5], cost = [3,4,5,1,2]) the diffs are [-2,-2,-2,3,3]. Starts move to 1, 2, 3 and then stay at 3 because the run balance grows to 3 and 6. The total is 0, so the answer is 3.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the number of stations. The loop visits each index once and does a constant amount of work per index, so time is n steps. Three integers hold all the state, so space is constant. The bound is tight, since any correct solution must read every station at least once.
PythonTested in our runner
from typing import List, Optional
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
total = 0
current = 0
start = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
current += diff
if current < 0:
# no station from start to i can work, try the next one
start = i + 1
current = 0
return start if total >= 0 else -1JavaTested in our runner
import java.util.*;
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, current = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
int diff = gas[i] - cost[i];
total += diff;
current += diff;
if (current < 0) {
start = i + 1;
current = 0;
}
}
return total >= 0 ? start : -1;
}
}C++Tested in our runner
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int total = 0, current = 0, start = 0;
for (int i = 0; i < (int)gas.size(); i++) {
int diff = gas[i] - cost[i];
total += diff;
current += diff;
if (current < 0) {
start = i + 1;
current = 0;
}
}
return total >= 0 ? start : -1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function(gas, cost) {
let total = 0, current = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const diff = gas[i] - cost[i];
total += diff;
current += diff;
if (current < 0) {
start = i + 1;
current = 0;
}
}
return total >= 0 ? start : -1;
};GoTested in our runner
func canCompleteCircuit(gas []int, cost []int) int {
total, current, start := 0, 0, 0
for i := 0; i < len(gas); i++ {
diff := gas[i] - cost[i]
total += diff
current += diff
if current < 0 {
start = i + 1
current = 0
}
}
if total >= 0 {
return start
}
return -1
}C#Tested in our runner
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, current = 0, start = 0;
for (int i = 0; i < gas.Length; i++) {
int diff = gas[i] - cost[i];
total += diff;
current += diff;
if (current < 0) {
start = i + 1;
current = 0;
}
}
return total >= 0 ? start : -1;
}
}Common mistakes
- Setting
start = iinstead ofstart = i + 1whencurrent < 0. The tank went negative while leaving stationi, so stationiitself failed as a start too. Move the candidate toi + 1. - Resetting
current = 0but forgetting to movestart. The balance restarts, yet the returned index still points at the failed run. Update both in the sameifblock. - Skipping the
total < 0check at the end. The greedy pass always leaves somestartbehind, even when no lap is possible. Return -1 whentotalis negative. - Testing
current <= 0instead ofcurrent < 0. A tank of exactly 0 is legal, and the unique answer can reach a station with an empty tank. Fail only on strictly negative. - Running the full simulation from each start with
forloops and no early exit, which is the O(n^2) trap. The fix is to stop when the tank goes negative, then use the skip rule so you never revisit those stations. - Simulating the wrap-around by looping over the array twice inside the greedy code. The total check already proves the wrap-around is safe, so a second lap adds code without adding correctness.
Edge cases
- A single station with gas[0] >= cost[0], for example gas = [5], cost = [4]. The answer is 0.
- A single station with gas[0] < cost[0], for example gas = [2], cost = [3]. The answer is -1.
- Total gas exactly equals total cost, as in Example 1. The tank reaches exactly 0 at the end, and the answer is still valid.
- Gas and cost both all zeros. Every net gain is 0 and the tank never goes negative, so the answer is 0. The uniqueness guarantee means such a test is unlikely, but the code returns 0.
- The valid start is the last index, for example gas = [1, 1, 5], cost = [2, 2, 1]. The candidate moves to 1, then 2, and stays there. The answer is 2.
- The valid start is index 0 and the net gains are positive first, for example gas = [3, 1, 1], cost = [1, 2, 2]. The run balance never drops below 0, so the answer is 0.
Follow-ups interviewers ask
- Why is it safe to skip every station between the failed start and the failure point?
- Say the run from s fails at i. For any k between s and i, you reached k with a non-negative tank, because the run had not failed yet. The sum of gains from k to i equals the sum from s to i minus the sum from s to k-1. The first is negative and the second is at least 0, so starting at k also fails by i.
- Why does a non-negative total guarantee the wrap-around works for the last candidate?
- Let c be the final candidate. The gains from c to the end have non-negative prefix sums, so you reach the end of the array with some tank S. Each earlier run ended negative, so any prefix of the gains before c is at least the sum D of all those earlier runs. Your tank while wrapping is at least S + D, which equals the total, and the total is at least 0.
- How would you return every valid start if the answer were not unique?
- Compute the prefix sums of the net gains and find the minimum prefix. Any index right after a position where the prefix sum reaches its minimum is a valid start when the total is non-negative. Scan once to find the minimum, then once more to collect all matching indices, which is still O(n) time.
Gas Station FAQ
What is the time complexity of Gas Station?
The greedy solution runs in O(n) time and O(1) space, where n is the number of stations. It reads each station once. The brute force simulation is O(n^2) because it replays up to n stations from each of n starts.
Why use a greedy approach for Gas Station?
A failed run tells you more than the failed start. It rules out every station inside that run, because each of them would begin with less fuel than the run had when it arrived. That lets you jump the candidate forward instead of retrying, which is a local choice that is always safe.
Can Gas Station be solved in O(1) extra space?
Yes. The greedy pass keeps only three integers: the total, the current run balance and the start index. It does not need a prefix array or a copy of the input.
Why is checking total gas against total cost enough?
If the total net gain is negative, a full lap needs more fuel than the stations hold, so no start works. If it is non-negative, the last candidate from the greedy pass works. Together these two facts cover every input.
Do I need to loop around the array twice for LeetCode 134?
No. Some solutions walk the array twice to simulate the wrap-around, but the total check replaces the second lap. One pass plus the total gives the same answer with less code.
What does the answer index mean in the Gas Station solution in Python or Java?
It is the station where you begin with an empty tank and fill up first. The car then moves clockwise to index + 1, wrapping from n - 1 to 0. Index 0 is a valid answer, so -1 is used as the no-solution marker.
Asked at
See which companies ask this — Pro
Related problems
- Candy · next harder, same pattern
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Non-overlapping Intervals · same pattern: Greedy Patterns
- Insert Interval · same pattern: Greedy Patterns
- Jump Game II · same pattern: Greedy Patterns
- Partition Labels · same pattern: Greedy Patterns
- Hand of Straights · same pattern: Greedy Patterns
- Merge Triplets to Form Target Triplet · same pattern: Greedy Patterns