Ecommet

Gas Station

Medium Problem 137 of 151 Java and Python

Problem

There are n gas stations on a circular route. Station i gives gas[i] fuel, and driving from station i to i + 1 costs cost[i]. You start with an empty tank at one station.

Return the index of the station where you can start and complete the circuit once, clockwise. If it is impossible, return -1. If a solution exists, it is unique.

Example 1

Input
gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]
Output
3

Example 2

Input
gas = [2, 3, 4], cost = [3, 4, 3]
Output
-1
Why
Total gas 9 < total cost 10.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ gas[i], cost[i] ≤ 10⁴

Explanation

If total gas is less than total cost, no start works. Otherwise one does.

Drive from a candidate start, keeping the tank. If the tank goes negative at station i, no station between the start and i can be the answer either (each would arrive at i with even less fuel). So jump the candidate to i + 1 and reset the tank.

Approach 1 · Naive

Try every start

  • Time O(n²)
  • Space O(1)

Simulate the full loop from each station.

  1. For each start, drive around, adding gas and subtracting cost.
  2. Return the first start whose tank never goes negative.
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 steps = 0;
            while (steps < n) {
                int i = (start + steps) % n;
                tank += gas[i] - cost[i];
                if (tank < 0) {
                    break;
                }
                steps++;
            }
            if (steps == n) {
                return start;
            }
        }
        return -1;
    }
}
Python
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas)
        for start in range(n):
            tank = 0
            for step in range(n):
                i = (start + step) % n
                tank += gas[i] - cost[i]
                if tank < 0:
                    break
            else:
                return start
        return -1

Approach 2 · Optimal

One pass, reset on failure

  • Time O(n)
  • Space O(1)

Track the total balance and the current tank; whenever the tank drops below zero, the next station becomes the candidate.

  1. total = tank = start = 0.
  2. For each i: diff = gas[i] - cost[i]; add it to total and tank.
  3. If tank < 0: start = i + 1, tank = 0.
  4. Return start if total >= 0, else -1.
Java
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int total = 0;
        int tank = 0;
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            int diff = gas[i] - cost[i];
            total += diff;
            tank += diff;
            if (tank < 0) {
                start = i + 1;
                tank = 0;
            }
        }
        return total >= 0 ? start : -1;
    }
}
Python
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        total = tank = start = 0
        for i in range(len(gas)):
            diff = gas[i] - cost[i]
            total += diff
            tank += diff
            if tank < 0:
                start, tank = i + 1, 0
        return start if total >= 0 else -1

Complexity compared

ApproachTimeSpace
Naive Try every startO(n²)O(1)
Optimal One pass, reset on failureO(n)O(1)

Key takeaways

  • The proof matters in interviews: failing at i rules out every start between the old candidate and i.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem