15% off all plans & roadmaps Use code

See plans

Gas Station

Updated

TL;DR: Find the one station where a full clockwise lap works, or return -1. Track the running fuel balance, restart the candidate whenever it goes negative, and check that total gas covers total cost.

Problem

There are n gas stations on a circular route. Station i holds gas[i] units of gas.

Your car has an unlimited tank. Driving from station i to station i + 1 costs cost[i] units of gas. You start at one station with an empty tank.

Given the arrays gas and cost, return the index of the station where you can start and drive once around the circuit clockwise. If no such station exists, return -1. If a solution exists, it is guaranteed to be unique.

Example 1

Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation: Start at station 3 and fill up with 4 units. The tank is 4. Drive to station 4: 4 - 1 + 5 = 8. Drive to station 0: 8 - 2 + 1 = 7. Drive to station 1: 7 - 3 + 2 = 6. Drive to station 2: 6 - 4 + 3 = 5. Drive back to station 3, which costs 5, and the tank holds exactly enough. Return 3.

Example 2

Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation: You cannot start at station 0 or 1, because you cannot reach the next station. Start at station 2 and fill up with 4 units. Drive to station 0: 4 - 3 + 2 = 3. Drive to station 1: 3 - 3 + 3 = 3. Returning to station 2 costs 4 but you hold only 3. No starting station works.

Constraints

  • n == gas.length == cost.length
  • 1 <= n <= 10^5
  • 0 <= gas[i], cost[i] <= 10^4
  • The input is generated so that the answer is unique.

Constraints that matter

  • n up to 10^5 rules out O(n^2). Simulating a full lap from every station means about 10^10 steps in the worst case, which times out.
  • The answer is unique when it exists, so the first valid start you find is the only one. You never need to compare candidates.
  • Values are at most 10^4 and n is at most 10^5, so any running sum stays within 10^9 in magnitude. A 32-bit int is safe in Java, C++ and C#.
  • gas[i] and cost[i] can be 0, so a station can give nothing or cost nothing. A tank of exactly 0 is still allowed, so test < 0 and never <= 0.
  • n can be 1. A single station works exactly when gas[0] >= cost[0], and the loops must handle that without special code.

View on LeetCode

Hints

Hint 1

This is a greedy problem built on prefix sums.

Hint 2

Treat every station as a possible start.

Solution

Intuition

This is a greedy problem built on prefix sums. Define the net gain at station i as gas[i] - cost[i]. The car survives a leg as long as the running sum of net gains never goes below zero.

Picture a single fuel gauge on one long road trip. The gauge is the running balance, and when it dips below zero you move the start to the next stop and reset the gauge to empty.

Two facts do all the work. First, if the total net gain over the whole circle is negative, no start can work, because a full lap consumes more than it collects. Second, if you start at s and the tank first goes negative at station i, then no station between s and i can be a good start either.

The second fact is the key. To reach any station k between s and i, you arrived with a tank of at least 0. Starting fresh at k gives you exactly 0, which is never more than what you had. If the longer trip from s failed at i, the trip from k fails at i or earlier. So you can skip every station up to i and try i + 1.

That turns n separate simulations into one pass. You keep one candidate start and one running balance. When the balance goes negative, you drop the candidate and move it forward. At the end, the total tells you whether the surviving candidate also survives the wrap-around.

Watch the pattern animation

Worked example

Input: gas = [2, 3, 4], cost = [3, 4, 3]
Output: -1
Explanation: The net gain per station (gas minus cost) is [-1, -1, 1]. These add up to -1, so the whole circuit holds less gas than it costs. No starting station can finish the lap.

Approach 1: Brute force

Treat every station as a possible start. For each one, simulate the lap: add gas[j] - cost[j] at each station, wrapping with modulo, and stop as soon as the tank goes below zero.

This is correct because it mirrors the problem exactly. It is slow because the simulations share nothing.

Steps

  1. Loop start from 0 to n - 1.
  2. Set tank = 0 for this start.
  3. Loop step from 0 to n - 1 and compute j = (start + step) % n.
  4. Add gas[j] - cost[j] to tank.
  5. If tank < 0, abandon this start and move to the next one.
  6. If all n steps finish with a non-negative tank, return start.
  7. If no start survives, return -1.

Dry run

Net gains are [-1, -1, 1].

  • Start 0: after station 0 the tank is -1. Fail.
  • Start 1: after station 1 the tank is -1. Fail.
  • Start 2: after station 2 the tank is 1. After station 0 it is 0. After station 1 it is -1. Fail.

No start survives, so the answer is -1.

Complexity

TimeO(n^2)
SpaceO(1)

Here n is the number of stations. The outer loop runs n times and the inner loop runs at most n times each, so the worst case is n * n steps. With n = 10^5 that is about 10^10 steps, too many for the time limit. The code keeps only a start index, a step index and a tank, so space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas)
        for start in range(n):
            tank = 0
            ok = True
            for step in range(n):
                j = (start + step) % n
                tank += gas[j] - cost[j]
                if tank < 0:
                    ok = False
                    break
            if ok:
                return start
        return -1

Approach 2: Two pointers on a growing window

What's slow: brute force restarts from scratch for each start, even though neighbouring starts cover almost the same stations. Each new start throws away all the fuel arithmetic from the last one.

The insight that fixes it: keep one window of consecutive stations and its tank balance. Begin with the window holding only the last station. If the balance is non-negative, extend the window forward by one station at the end pointer.

If the balance is negative, the start is wrong. Extend the window backward by one station at the start pointer, which adds a new gain at the front. Each step adds exactly one station to the window.

Steps

  1. Set start = n - 1 and end = 0. Set tank = gas[start] - cost[start].
  2. Loop while start > end. The window then holds n - 1 - end + 1 plus end stations, fewer than n.
  3. If tank >= 0, add the net gain at end to tank and do end += 1.
  4. Otherwise do start -= 1 and add the net gain at the new start to tank.
  5. When the pointers meet, the window covers all n stations once, so tank equals the total net gain.
  6. Return start if tank >= 0, else return -1.

Dry run

Net gains are [-1, -1, 1]. Start with start = 2, end = 0, tank = 1.

  • tank = 1 >= 0, so add the gain at index 0: tank becomes 0, end = 1.
  • tank = 0 >= 0, so add the gain at index 1: tank becomes -1, end = 2.
  • Now start == end, so the loop stops. The window covers every station.
  • tank = -1 < 0, so return -1.

Complexity

TimeO(n)
SpaceO(1)

Here n is the number of stations. The window starts with one station and each loop iteration adds one more, either at the front or the back. The loop stops when the pointers meet, so it runs at most n - 1 times. Only four integers are stored.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas)
        start, end = n - 1, 0
        tank = gas[start] - cost[start]
        while start > end:
            if tank >= 0:
                # window is healthy, extend it forward
                tank += gas[end] - cost[end]
                end += 1
            else:
                # window is short of fuel, extend it backward
                start -= 1
                tank += gas[start] - cost[start]
        if tank < 0:
            return -1
        # prefer the smallest valid index: j < start is valid iff P[j] <= min(P[j+1..start])
        best = start
        rel = 0  # P[j] - P[start], tracked while walking back
        m = 0    # min of P[k]-P[start] for k in (j, start]
        for j in range(start - 1, -1, -1):
            rel -= gas[j] - cost[j]
            if rel <= m:
                best = j
                m = rel
        return best
Gas Station Circuit pattern infographic for Gas Station

Solution pattern

Gas Station Circuit

Part of Greedy Patterns

Approach 3: One-pass greedyOptimalGas Station Circuit

What's slow: the two-pointer window still makes you reason about growing in two directions, and it is easy to get the pointer moves wrong. Brute force also repeats work after every failure.

The insight that fixes it: when a run starting at s fails at i, every station from s to i is ruled out, so jump the candidate to i + 1 and reset the run balance. Walk the array once, keep a running total of all net gains, and keep a run balance that resets on failure. At the end, a negative total means -1. Otherwise the last candidate is the answer.

Steps

  1. Set total = 0, current = 0 and start = 0.
  2. For each index i, compute diff = gas[i] - cost[i].
  3. Add diff to both total and current.
  4. If current < 0, set start = i + 1 and current = 0.
  5. After the loop, return -1 if total < 0.
  6. Otherwise return start.

Dry run

Trace on gas = [2, 3, 4], cost = [3, 4, 3].

idifftotalcurrent before resetstart
0-1-1-1, below 0, reset to 01
1-1-2-1, below 0, reset to 02
21-11, stays2

The loop ends with total = -1, which is below 0, so the answer is -1.

On Example 1 (gas = [1,2,3,4,5], cost = [3,4,5,1,2]) the diffs are [-2,-2,-2,3,3]. Starts move to 1, 2, 3 and then stay at 3 because the run balance grows to 3 and 6. The total is 0, so the answer is 3.

Complexity

TimeO(n)
SpaceO(1)

Here n is the number of stations. The loop visits each index once and does a constant amount of work per index, so time is n steps. Three integers hold all the state, so space is constant. The bound is tight, since any correct solution must read every station at least once.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        total = 0
        current = 0
        start = 0
        for i in range(len(gas)):
            diff = gas[i] - cost[i]
            total += diff
            current += diff
            if current < 0:
                # no station from start to i can work, try the next one
                start = i + 1
                current = 0
        return start if total >= 0 else -1

Common mistakes

  • Setting start = i instead of start = i + 1 when current < 0. The tank went negative while leaving station i, so station i itself failed as a start too. Move the candidate to i + 1.
  • Resetting current = 0 but forgetting to move start. The balance restarts, yet the returned index still points at the failed run. Update both in the same if block.
  • Skipping the total < 0 check at the end. The greedy pass always leaves some start behind, even when no lap is possible. Return -1 when total is negative.
  • Testing current <= 0 instead of current < 0. A tank of exactly 0 is legal, and the unique answer can reach a station with an empty tank. Fail only on strictly negative.
  • Running the full simulation from each start with for loops and no early exit, which is the O(n^2) trap. The fix is to stop when the tank goes negative, then use the skip rule so you never revisit those stations.
  • Simulating the wrap-around by looping over the array twice inside the greedy code. The total check already proves the wrap-around is safe, so a second lap adds code without adding correctness.

Edge cases

  • A single station with gas[0] >= cost[0], for example gas = [5], cost = [4]. The answer is 0.
  • A single station with gas[0] < cost[0], for example gas = [2], cost = [3]. The answer is -1.
  • Total gas exactly equals total cost, as in Example 1. The tank reaches exactly 0 at the end, and the answer is still valid.
  • Gas and cost both all zeros. Every net gain is 0 and the tank never goes negative, so the answer is 0. The uniqueness guarantee means such a test is unlikely, but the code returns 0.
  • The valid start is the last index, for example gas = [1, 1, 5], cost = [2, 2, 1]. The candidate moves to 1, then 2, and stays there. The answer is 2.
  • The valid start is index 0 and the net gains are positive first, for example gas = [3, 1, 1], cost = [1, 2, 2]. The run balance never drops below 0, so the answer is 0.

Follow-ups interviewers ask

Why is it safe to skip every station between the failed start and the failure point?
Say the run from s fails at i. For any k between s and i, you reached k with a non-negative tank, because the run had not failed yet. The sum of gains from k to i equals the sum from s to i minus the sum from s to k-1. The first is negative and the second is at least 0, so starting at k also fails by i.
Why does a non-negative total guarantee the wrap-around works for the last candidate?
Let c be the final candidate. The gains from c to the end have non-negative prefix sums, so you reach the end of the array with some tank S. Each earlier run ended negative, so any prefix of the gains before c is at least the sum D of all those earlier runs. Your tank while wrapping is at least S + D, which equals the total, and the total is at least 0.
How would you return every valid start if the answer were not unique?
Compute the prefix sums of the net gains and find the minimum prefix. Any index right after a position where the prefix sum reaches its minimum is a valid start when the total is non-negative. Scan once to find the minimum, then once more to collect all matching indices, which is still O(n) time.

Gas Station FAQ

What is the time complexity of Gas Station?

The greedy solution runs in O(n) time and O(1) space, where n is the number of stations. It reads each station once. The brute force simulation is O(n^2) because it replays up to n stations from each of n starts.

Why use a greedy approach for Gas Station?

A failed run tells you more than the failed start. It rules out every station inside that run, because each of them would begin with less fuel than the run had when it arrived. That lets you jump the candidate forward instead of retrying, which is a local choice that is always safe.

Can Gas Station be solved in O(1) extra space?

Yes. The greedy pass keeps only three integers: the total, the current run balance and the start index. It does not need a prefix array or a copy of the input.

Why is checking total gas against total cost enough?

If the total net gain is negative, a full lap needs more fuel than the stations hold, so no start works. If it is non-negative, the last candidate from the greedy pass works. Together these two facts cover every input.

Do I need to loop around the array twice for LeetCode 134?

No. Some solutions walk the array twice to simulate the wrap-around, but the total check replaces the second lap. One pass plus the total gives the same answer with less code.

What does the answer index mean in the Gas Station solution in Python or Java?

It is the station where you begin with an empty tank and fill up first. The car then moves clockwise to index + 1, wrapping from n - 1 to 0. Index 0 is a valid answer, so -1 is used as the no-solution marker.

Asked at

See which companies ask this — Pro

Practise it