150NeetCode 150

125.Gas Station

MediumGreedy Ā· 4/8

Problem

There are n gas stations on a circular route. Station i provides gas[i] units of fuel, and driving from station i to station i + 1 (wrapping around) costs cost[i] units. Your car starts with an empty tank and has unlimited capacity.

Return the index of the starting station from which you can travel around the circuit once clockwise, or -1 if it is impossible. If a solution exists, it is guaranteed to be unique.

Examples

Input:  gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation: Start at 3: tank 4-1=3, +5-2=6, +1-3=4, +2-4=2, +3-5=0. Back at 3 with 0 >= 0.
Input:  gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation: Total gas 9 < total cost 10, so no start works.

Constraints

  • n == gas.length == cost.length
  • 1 <= n <= 10^5
  • 0 <= gas[i], cost[i] <= 10^4
  • The answer, if it exists, is unique.

šŸ’” Key Insight

Let diff[i] = gas[i] - cost[i]. A full loop is possible iff sum(diff) >= 0. And if the tank goes negative while driving from start to station i, then no station between start and i can be a valid start either — each of them would begin with less fuel than we had when passing it (we arrived there with a non-negative tank). So we can jump the candidate start straight to i + 1, giving a one-pass greedy.

Brute Force Simulation

TimeO(n²)SpaceO(1).

Intuition

Try each station as the start and simulate the trip around the circle, failing as soon as the tank goes negative.

Algorithm

  1. For each start in 0..n-1:
  2. tank = 0; for k in 0..n-1: i = (start + k) % n, tank += gas[i] - cost[i]; break if tank < 0.
  3. If the loop finished, return start.
  4. Return -1.

Visualization

diff = gas - cost = [-2, -2, -2, 3, 3]

start 0: -2 < 0 fail
start 1: -2 fail
start 2: -2 fail
start 3: 3, 6, 4, 2, 0  -> never negative -> return 3

Code

java
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        for (int start = 0; start < n; start++) {
            int tank = 0;
            int k = 0;
            for (; k < n; k++) {
                int i = (start + k) % n; // wrap around the circle
                tank += gas[i] - cost[i];
                if (tank < 0) {
                    break;
                }
            }
            if (k == n) {
                return start; // completed the full loop
            }
        }
        return -1;
    }
}

Complexity

  • Time: O(n²) — up to n simulations of length n.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force Simulation O(n²) O(1)
Minimum Prefix Sum O(n) O(1)
Greedy One Pass O(n) O(1)

Common Pitfalls

  • Resetting start to i instead of i + 1 — station i itself is part of the failing segment.
  • Forgetting the global total >= 0 check; the greedy's final start is only meaningful when the total is non-negative.
  • Worrying that start could become n: that only happens when total < 0 (the last segment was negative), in which case we return -1 anyway.
  • Comparing gas[i] >= cost[i] alone to pick a start — a station with a local surplus can still fail later.