134. Gas Station
Asked at 27Bloomberg55Amazon52Microsoft49Apple40Google39Meta34Sprinklr82Infosys76Adobe63TikTok46Goldman Sachs40CME Group100Scale AI100BitGo84Mastercard75Flipkart72Accolite70Dream1168PhonePe64Tekion63Zoho60Visa55ServiceNow55Oracle49Juspay47Salesforce41tcs27
Problem
Gas stations stand on a circular route; station i has gas[i] fuel, and driving from it to station i + 1 costs cost[i]. Starting with an empty tank, return the station from which you can drive around the whole circuit once, or −1 if none works. The answer is unique when it exists.
Example: gas = [1,2,3,4,5], cost = [3,4,5,1,2] → 3
Constraints: n ≤ 10⁵.
If total gas < total cost → impossible. Otherwise, scan with a running tank; whenever it drops below 0, no station in the current segment can be the start → restart from i + 1.
Complexity: O(n).
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):
return -1
start = tank = 0
for i, (g, c) in enumerate(zip(gas, cost)):
tank += g - c
if tank < 0:
start, tank = i + 1, 0
return start
assert Solution().canCompleteCircuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) == 3
assert Solution().canCompleteCircuit([2, 3, 4], [3, 4, 3]) == -1
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, tank = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
total += gas[i] - cost[i];
tank += gas[i] - cost[i];
if (tank < 0) { start = i + 1; tank = 0; }
}
return total < 0 ? -1 : start;
}
}
func canCompleteCircuit(gas []int, cost []int) int {
total, tank, start := 0, 0, 0
for i := range gas {
total += gas[i] - cost[i]
tank += gas[i] - cost[i]
if tank < 0 { // cannot reach i+1 from start, nor from any station in between
start, tank = i+1, 0
}
}
if total < 0 {
return -1
}
return start
}