Gas Station

Medium

Topics
ArrayGreedy

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

gas1623
cost4132
net-35-11
the only possible start
The third row is 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.
Rows are gas available, cost to leave, and their difference.
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

gas22
cost32
net-10
The total is negative, so no start works and the answer is -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

  1. Track total (sum of gas[i] - cost[i] over all stops), tank and start = 0.
  2. For each stop, add gas[i] - cost[i] to both total and tank.
  3. If tank drops below 0, set start = i + 1 and tank = 0.
  4. After the loop, return start if total >= 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 start without checking total gives 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 start
SensAI
Beta
Tap the mic to stop voice mode