Gas Station
Medium
Topics
A delivery van drives a one-way ring road with n fuel stops numbered 0 to n - 1. At stop i it can take on gas[i] units of fuel, and driving from stop i to the next stop, (i + 1) mod n, burns cost[i] units. The tank has no upper limit and starts empty.
Return the index of the stop where the van should start so that it can visit every stop once and arrive back where it began without the tank ever going negative. Return -1 if no start works. Inputs are chosen so that at most one start works.
Example 1
gas − cost per station. Two facts settle it: a loop is possible only if that row sums to ≥ 0, and if the tank goes negative at station i then no station up to i can be the start.Input: gas = [1,6,2,3], cost = [4,1,3,2] Output: 1 Explanation: From stop 1 the tank reads 5, 4, 5 and 2 after each leg; it never dips below 0.
Example 2
-1.Input: gas = [2,2], cost = [3,2] Output: -1 Explanation: Total fuel 4 is less than the total cost 5.
Constraints
- n == gas.length == cost.length
- 1 <= n <= 10^5
- 0 <= gas[i], cost[i] <= 10^4
- At most one starting stop completes the loop.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two facts do all the work. First, if total fuel is less than total cost, no start can work. Second, if you start at s and first run dry on the leg out of stop t, then no stop between s and t can be the start either: you reached each of them with a non-negative tank, so starting there empty is no better.
So whenever the tank goes negative, jump the candidate start to the next stop and reset the tank. One pass finds the only candidate.
Approach
- Track
total(sum ofgas[i] - cost[i]over all stops),tankandstart = 0. - For each stop, add
gas[i] - cost[i]to bothtotalandtank. - If
tankdrops below 0, setstart = i + 1andtank = 0. - After the loop, return
startiftotal >= 0, otherwise-1.
Dry Run
gas = [1, 6, 2, 3]
cost = [4, 1, 3, 2]
gas - cost at each stop: -3 +5 -1 +1 total +2, so some start works
i=0 delta -3 tank -3 -> negative, so start jumps to 1 and tank resets to 0
i=1 delta +5 tank 5 start 1
i=2 delta -1 tank 4 start 1
i=3 delta +1 tank 5 start 1
answer 1
The jump at i=0 does more than discard stop 0. It discards every stop from the old
start through i. If you arrived at some stop j with a non-negative tank and still
ran dry at i, then beginning at j with an empty tank cannot do better than that,
so the next candidate is i + 1 and nothing in between is worth trying. That single
observation is what collapses an O(n^2) simulation into one pass.
total and tank are two counters answering two different questions, which is why
only one of them is ever reset. total answers "is any start possible at all";
tank answers "has THIS candidate survived so far". Drop the total check and
gas [2,2] against cost [3,2] returns 1 instead of -1 -- a confident index for a
circuit that cannot be completed.
Note the loop never wraps around. It does not need to: if the totals balance,
exactly one candidate survives to the end, and the proof above says it is the
right one.Complexity
- Time — O(n): a single pass.
- Space — O(1): three counters.
Common Pitfalls
- Simulating the loop from every start is O(n2) and times out at n = 10^5.
- Returning
startwithout checkingtotalgives a wrong index when no answer exists.
Full Solution — all languages
class Solution:
def canCompleteCircuit(self, gas, cost):
if sum(gas) < sum(cost):
return -1
start = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
tank = 0
return startimport java.util.*;
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
long totalGas = 0, totalCost = 0;
for (int i = 0; i < gas.length; i++) {
totalGas += gas[i];
totalCost += cost[i];
}
if (totalGas < totalCost) return -1;
int start = 0;
long tank = 0;
for (int i = 0; i < gas.length; i++) {
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return start;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
long long totalGas = 0, totalCost = 0;
for (size_t i = 0; i < gas.size(); i++) {
totalGas += gas[i];
totalCost += cost[i];
}
if (totalGas < totalCost) return -1;
int start = 0;
long long tank = 0;
for (size_t i = 0; i < gas.size(); i++) {
tank += gas[i] - cost[i];
if (tank < 0) {
start = (int)i + 1;
tank = 0;
}
}
return start;
}
};/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/ var canCompleteCircuit = function(gas, cost) {
let totalGas = 0, totalCost = 0;
for (let i = 0; i < gas.length; i++) {
totalGas += gas[i];
totalCost += cost[i];
}
if (totalGas < totalCost) return -1;
let start = 0, tank = 0;
for (let i = 0; i < gas.length; i++) {
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return start;
};