Gas Station
Difficulty: Medium
Gas stations are arranged in a circle. At station i you pick up gas[i] fuel, and driving to the next station costs cost[i] fuel. You start with an empty tank at a station of your choice.
Return the starting station's index that lets you drive the full circle without the tank going negative. If no start works, return -1. If an answer exists, it's unique.
Examples
Input: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]
Output: 3
Starting at station 3: tank = 4-1=3, then +5-2=6, then +1-3=4, then +2-4=2, then +3-5=0. You never go negative and make it all the way around.
Input: gas = [2, 3, 4], cost = [3, 4, 3]
Output: -1
Total gas (9) is less than total cost (10), so no starting point can complete the circuit.
Constraints
n == gas.length == cost.length
1 <= n <= 10^5
0 <= gas[i], cost[i] <= 10^4
Approach
Simulating the loop from every station works but is slow.
First, if total gas is less than total cost, no start works. Otherwise a solution exists, and one pass finds it.
Walk around once from station 0 with a running tank. When it goes negative, none of the stations since the current candidate start could work either: starting later only gives a smaller-or-equal tank at each point. So move the candidate start to the next station.
Solutions
Brute Force - Simulate From Every Start
From every station, simulate a full trip, giving up as soon as the tank goes negative.
function canCompleteCircuit(gas, cost) {
const n = gas.length;
for (let start = 0; start < n; start++) {
let tank = 0;
let steps = 0;
for (; steps < n; steps++) {
const i = (start + steps) % n;
tank += gas[i] - cost[i];
if (tank < 0) break;
}
if (steps === n) return start;
}
return -1;
}Time: O(n^2) · Space: O(1)
Optimal - Greedy One Pass
Compare total gas to total cost to see if any start works. Find the start by moving the candidate forward each time the running tank goes negative.
function canCompleteCircuit(gas, cost) {
let totalTank = 0;
let currTank = 0;
let start = 0;
for (let i = 0; i < gas.length; i++) {
const diff = gas[i] - cost[i];
totalTank += diff;
currTank += diff;
if (currTank < 0) {
start = i + 1;
currTank = 0;
}
}
return totalTank < 0 ? -1 : start;
}Time: O(n) · Space: O(1)