Algo-Sim › Greedy

Gas Station

Medium · Greedy · step through it in Java, Python and C++ on your own input

Find the station to start from to drive the whole loop, or -1. When the tank goes negative, every start so far is ruled out at once.

Problem

Gas stations sit on a circular road. Station i gives you gas[i] units, and driving on to station i + 1 uses cost[i]. Starting with an empty tank, return the index of the station from which you can drive one full lap, or -1 if no start works. If a start exists, it is unique.

Constraints

Edge cases to test

Follow-up questions

Why can the start jump past every failed station?
If you run dry at j starting from i, every start between i and j had a non-negative tank on arrival and would fail at j too.
Why does a full loop work once total gas ≥ total cost?
The deficit before the chosen start is covered by the surplus after it, because the totals balance: one O(n) pass.

Solution

Java

public int canCompleteCircuit(int[] gas, int[] cost) {
    int total = 0, tank = 0, 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

def can_complete_circuit(gas, cost):
    total = tank = start = 0
    for i in range(len(gas)):
        diff = gas[i] - cost[i]
        total += diff
        tank += diff
        if tank < 0:
            start = i + 1
            tank = 0
    return start if total >= 0 else -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int total = 0, tank = 0, start = 0;
        for (int i = 0; i < int(gas.size()); i++) {
            int diff = gas[i] - cost[i];
            total += diff;
            tank += diff;
            if (tank < 0) {
                start = i + 1;
                tank = 0;
            }
        }
        return total >= 0 ? start : -1;
    }
};

More Greedy problems