Gas Station solution explained
Gas Station has a one-pass greedy answer. If the total fuel on the loop is less than the total cost, no start works. Otherwise, drive from station 0 keeping a running tank, and whenever the tank drops below zero, declare the next station the new start and empty the tank. The last start you declared is a valid one, and the whole check takes O(n) time.
By Evin JohnPublished 8 min read
The problem, reworded
There are n refuelling stops arranged in a circle. At stop k you collect fuel[k] units, and driving on to stop k + 1 (or back to stop 0 from the last one) uses cost[k] units. Your tank has no upper limit and starts empty. Choose a starting stop so that you can visit every stop once and arrive back where you began without the tank ever going below zero. Return that stop's index, or -1 if none exists.
| fuel | cost | Answer | Note |
|---|---|---|---|
[4, 1, 2, 6] | [3, 3, 4, 2] | 3 | Only stop 3 works |
[5, 0, 3] | [2, 4, 1] | 2 | Starting at 0 runs dry on the leg out of stop 1 |
[2, 2, 2] | [3, 2, 2] | -1 | Total fuel 6 is less than total cost 7 |
[1, 1] | [1, 1] | 0 | Both stops work; the code returns the lower index |
The usual version promises that when an answer exists, it is unique. Ask about that, because if several stops can work, you should agree on which one to return. The method below always returns the lowest-numbered stop that works, and the argument for why is short enough to give in the room.
What it tests
The code is a handful of lines, so the interview is about the reasoning. Can you turn a circular simulation into a linear scan, and can you prove that resetting the start is safe instead of hoping it is? Interviewers often follow the code with a direct question: why can you skip every stop between the old start and the failure point? Prepare that answer before anything else.
Brute force: try every stop
For each candidate start, drive around the loop adding fuel and subtracting cost, and abandon the candidate the moment the tank goes negative. The first candidate that survives a full lap is an answer. Each simulation is up to n legs and there are n candidates, so this is O(n²). It is a correct baseline and a good way to generate test answers for the faster version.
def starting_pump_slow(fuel, cost):
n = len(fuel)
for start in range(n):
tank = 0
for step in range(n):
k = (start + step) % n
tank += fuel[k] - cost[k]
if tank < 0:
break
else:
return start
return -1Three facts that remove the inner loop
- Not enough fuel overall means no answerOver one full lap you collect every fuel value and pay every cost exactly once, whatever the start. If the sum of fuel is less than the sum of cost, the tank must end below zero, so return -1.
- A failed stretch rules out everything inside itSay you start at stop s and the tank first goes negative on the leg out of stop k. Every stop j between s and k was reached with zero or more fuel in the tank. Starting fresh at j means arriving there with exactly zero, which is never better, so the trip from j also fails by the leg out of k. Skip straight to k + 1.
- The survivor completes the loopAfter the scan, the last declared start reaches the end of the array without going negative. The legs before it, wrapped around, add up to the total minus what you already gained, and with a non-negative total the wrap-around never pushes the tank below zero.
def starting_pump(fuel, cost):
if sum(fuel) < sum(cost):
return -1 # not enough fuel on the whole loop
start = 0
tank = 0
for k in range(len(fuel)):
tank += fuel[k] - cost[k]
if tank < 0:
# no station from start to k can be the answer
start = k + 1
tank = 0
return startfunction startingPump(fuel, cost) {
let total = 0;
let tank = 0;
let start = 0;
for (let k = 0; k < fuel.length; k++) {
const gain = fuel[k] - cost[k];
total += gain;
tank += gain;
if (tank < 0) {
start = k + 1;
tank = 0;
}
}
return total < 0 ? -1 : start;
}Seeing it as a balance chart
The third step is easiest to believe with a running balance. Let the gain at each stop be fuel minus cost, and plot the running total as you go from stop 0. A start works exactly when, measured from that start, the line never dips below where it began. The best place to begin is right after the line's lowest point, since everything after the lowest point is higher than it. The reset rule finds exactly that point: every reset happens when the balance hits a new low.
| After stop | Gain at this stop | Running balance | Greedy start after this stop |
|---|---|---|---|
| (start) | 0 | 0 | |
| 0 | +1 | 1 | 0 |
| 1 | -2 | -1 (new low) | 2, tank reset |
| 2 | -2 | -3 (new low) | 3, tank reset |
| 3 | +4 | 1 | 3 |
The lowest point, -3, comes after stop 2, so stop 3 is the start. From there the tank reads 4, then 5 after stop 0, 3 after stop 1 and 1 after stop 2: never negative. The final balance of 1 is the total surplus, which is why the total check and the chart agree.
This also explains the tie behavior. Any stop before the first lowest point would see the balance fall below its own starting level on the way to that low, so it fails. The first stop after the lowest point is therefore the lowest index that can work, and that is the one the code returns.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Simulate from every stop | O(n²) | O(1) |
| Total check plus reset scan | O(n) | O(1) |
Edge cases
- One stop: it works exactly when its fuel covers its own cost back to itself.
- Total fuel equal to total cost: still possible. The tank ends at exactly zero, which is allowed.
- Stops with zero fuel or zero cost are ordinary gains of zero or negative values; nothing special is needed.
- A failure on the very last leg: the reset would point past the end, but that can only happen when the total is negative, which the total check already catches.
Mistakes that come up
- Resetting the start to k instead of k + 1. Stop k is part of the failed stretch.
- Skipping the total check and returning the last start regardless. Without the check, an impossible input still returns an index.
- Simulating a second lap with modulo indexing to be safe. It works but hides that you do not trust your own proof.
- Mixing up which leg cost[k] pays for. Restate it before coding: cost[k] is the trip out of stop k.
Follow-up questions
- Return every stop that works. Compute the running balance, then a stop works if the balance never drops below its starting level during the lap that begins there. A sweep that tracks minimum balances from both sides gives all of them in O(n).
- The tank has a maximum capacity. The reset argument breaks, because fuel above the cap is wasted and starting with an empty tank is no longer the worst case. Fall back to simulation and say why the proof no longer holds.
- One-way roads that are not a loop. Then there is only one possible start, the first stop, and the check is a single pass.
- Why is this like maximum subarray? Both scans keep a running sum and throw it away when it turns negative, since a negative prefix can only hurt what comes after.
Explaining it
Fictional example
- Candidate
- First, if total fuel is less than total cost, no start can work, so I return -1.
- Candidate
- Otherwise I drive from stop 0 with a running tank. If it goes negative after stop k, none of the stops from my start through k can work, because each of them was reached with a non-negative tank, and starting there empty is no better. So I restart at k + 1 with an empty tank.
- Candidate
- The last start I set is the answer: it is the stop right after the lowest point of the running balance. One pass, constant space.
Related walkthroughs
Jump Game is another greedy scan that keeps one running number and needs a short argument to be trusted. Partition Labels also makes a single left-to-right pass where one boundary keeps moving until a condition closes a segment. All walkthroughs are on the coding problems hub.
Where Natively helps in prep
During practice on Mac or Windows, you can have Natively read a problem like this from a screenshot and test your proof of the reset rule by asking it for the step you skipped. It transcribes the mock session and keeps notes, so you can see later whether your explanation of the total check came out in the right order. The AI interview assistant page has more.
Questions people ask
How do you solve the Gas Station problem?
If total fuel is less than total cost, return -1. Otherwise drive from station 0 with a running tank, and whenever it goes negative after station k, set the start to k + 1 and empty the tank. The final start is the answer.
Why can Gas Station skip the stations inside a failed stretch?
Each of those stations was reached with zero or more fuel. Starting there with an empty tank is never better, so a trip from any of them fails by the same point.
What is the time complexity of Gas Station?
The greedy is O(n) time and O(1) space. Simulating the trip from every station is O(n²).
What if more than one station works in Gas Station?
The usual version promises a unique answer. The reset method returns the lowest-numbered station that works, which is the first station after the lowest point of the running balance.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
