</>

134. Gas Station

Medium NeetCode 150
Greedy Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Greedy
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven two arrays representing the gas available and cost to travel at each station on a circular route, find the unique starting station index from which you can complete the full loop, or return -1 if no such station exists.

Approach
  • Compute net[i] = gas[i] - cost[i]; if the total sum is negative, no solution exists.
  • Use a single pass with a running tank balance. Whenever the tank drops below zero, the current candidate start cannot work — reset the tank to zero and try the next station as a new candidate.
  • Because a solution is guaranteed to be unique when the total net gas is non-negative, the candidate recorded after exhausting all stations is the answer.
  • This works because any prefix where the tank goes negative proves every station in that prefix is an invalid starting point.
#include <vector>
using namespace std;

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int totalNet = 0;   // sum of all (gas[i] - cost[i])
        int tank      = 0;  // running balance from the current candidate start
        int start     = 0;  // current candidate starting station

        for (int i = 0; i < (int)gas.size(); ++i) {
            int net = gas[i] - cost[i];
            totalNet += net;
            tank     += net;

            // If we can't reach station i+1, no station in [start..i] can be the answer.
            // Reset and try i+1 as the new candidate.
            if (tank < 0) {
                tank  = 0;
                start = i + 1;
            }
        }

        // If total net gas is negative the circuit is impossible.
        return (totalNet >= 0) ? start : -1;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
#include <climits>
using namespace std;

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

        int minDiff=INT_MAX;
        int minIdx=-1;
        for(int i=0; i<len; ++i){
            if(minDiff>gas[i]){
                minDiff=gas[i];
                minIdx=i;
            }
        }

        return (minIdx+1)%len;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern