TRT
Sign in
mediumAdvancedLeetCode#greedy restart#prefix balance

Gas station

Find the starting station for a circular route in one pass, using the total balance and the running tank.

The Runtime Theory Team1 min read
Taught inWhen greedy worksPro — members onlyA greedy algorithm makes the locally best choice at each step and never reconsiders it. It is fast and simple, and it is correct only when the problem has a specific structure, which you must prove or disprove.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ingas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]

out3

ingas = [2, 3, 4], cost = [3, 4, 3]

out-1

ingas = [5], cost = [4]

out0

Station i gives gas[i]; driving to the next station costs cost[i]. Return the station from which you can complete the circuit with an initially empty tank, or -1. The answer, if it exists, is unique.

Before you code

If total gas is less than total cost, no start works. Otherwise, a start fails exactly when the tank goes negative somewhere, and then no station between the start and that point can work either.

Hints

  1. Track the total balance and a running tank.
  2. When the tank goes negative at station i, set the start to i + 1 and reset the tank to 0.
  3. If the total is non-negative, the last start chosen is the answer.

Production & complexity notes

When solving Gas station on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in When greedy works to reinforce the underlying pattern.

What it practices

Proving a greedy restart rule, from When greedy works.

Not started

Sign in to save your learning progress.

Sign in to save