Gas Station — Solution in Python, Java & C++
Gas Station solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem on arrays and greedy.
Gas Station is a medium coding problem on arrays and greedy, asked in Sprinklr and Dream11 interviews.
- Difficulty: Medium
- Topics: Arrays, Greedy
- Asked at: Sprinklr, Dream11
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
There are n gas stations around a circular route; station i has gas[i] fuel, and driving to station i+1 costs cost[i]. You start with an empty tank at some station.
Return the starting station's index from which you can travel around the circuit once clockwise — or -1 if impossible. If a solution exists, it is unique.
Example 1
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Example 2
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Constraints
1 <= gas.length == cost.length <= 300 <= gas[i], cost[i] <= 20
Hints for Gas Station
Hint 1
If total gas < total cost, the answer is -1; otherwise a unique start exists.
Hint 2
If your tank goes negative arriving at i+1, no station ≤ i can be the start — restart from i+1.
How to solve Gas Station
Two independent facts settle this in one pass. First, a full loop is possible iff total gas is at least total cost — otherwise you run dry somewhere no matter where you begin. Second, if the tank goes negative on the way from start to i + 1, then no station in start..i can be the answer, so the search can skip straight past all of them.
Approach
- Track
total(overall gas minus cost) andtank(fuel since the current candidate start). - For each station
i, addgas[i] - cost[i]to both. - If
tankdrops below zero, discard the current candidate: setstart = i + 1and resettank = 0. - After the sweep, return
-1iftotal < 0, otherwisestart.
Why it works
The skip is the interesting half. Suppose starting at start fails on the way to i + 1. Any station j strictly between start and i begins with an empty tank, whereas a run from start arrives at j with a non-negative tank — otherwise it would have failed earlier. So starting at j is no better and fails too. That lets one linear scan rule out whole blocks at once. And when total >= 0, the last surviving candidate must work, because every prefix discarded before it had negative sum, forcing the remainder to be non-negative throughout.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- You need both accumulators:
tankfinds the candidate,totaldecides whether an answer exists at all. - Reset the tank to
0, not to the negative value, when moving the candidate start. - Do not wrap around and simulate the circle — one linear pass is enough, and simulating is
O(n^2). - The problem guarantees uniqueness, so there is no tie to break.
Reference solution
Python
from typing import List
def canCompleteCircuit(gas: List[int], cost: List[int]) -> int:
total = 0
tank = 0
start = 0
for i in range(len(gas)):
d = gas[i] - cost[i]
total += d
tank += d
if tank < 0:
start = i + 1
tank = 0
return -1 if total < 0 else startJava
public static int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, tank = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
int diff = gas[i] - cost[i];
total += diff;
tank += diff;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total < 0 ? -1 : start;
}C++
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int total = 0, tank = 0, start = 0;
for (int i = 0; i < (int) gas.size(); i++) {
int diff = gas[i] - cost[i];
total += diff;
tank += diff;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total < 0 ? -1 : start;
}JavaScript
var canCompleteCircuit = function(gas, cost) {
let total = 0, tank = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const d = gas[i] - cost[i];
total += d;
tank += d;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total < 0 ? -1 : start;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Greedy Algorithms