Gas Station

35 min · canCompleteCircuit()

A road trip around a loop has no finish line — unless your fuel tank forces one.

There are n stations on a circular route. Station i gives you gas[i] units of fuel, and driving from station i to the next station costs cost[i] units. You begin with an empty tank at one station, collect its fuel, and drive in the forward direction.

Return the index of the station from which you can complete one full circuit. Return -1 if no starting station works. Whenever a working start exists, it is unique.

A few ground rules:

  • The station after index n - 1 is index 0.
  • Your tank may reach exactly zero, but it may never become negative during the trip.
  • You collect a station's fuel before paying the cost to leave it.

Constraints

  • 1 <= gas.length == cost.length <= 10_000
  • 0 <= gas[i], cost[i] <= 10_000
  • If a valid starting index exists, it is unique.

Hints

Prove it by simulation

Try each station as the start. Walk at most n legs, updating the tank after every station. This reveals the exact condition that makes a candidate fail.

A failed stretch eliminates more than one start

Suppose you start at start and first run out after station i. Could any station between start and i have done better over the remaining part of that same stretch?

Separate local failure from global supply

Reset the candidate after every negative running tank. Separately track total fuel minus total cost; a negative total makes every starting point impossible.

Follow-up

If several starts were allowed to work, could you return all of them without simulating an entire circuit from every station?

Visible cases

Examples

Example 1

ready
Input
gas = [
  1,
  2,
  3,
  4,
  5
]
cost = [
  3,
  4,
  5,
  1,
  2
]
Expected
3
Why
starting at index 3 builds enough fuel to survive the wrap

Example 2

ready
Input
gas = [
  2,
  3,
  4
]
cost = [
  3,
  4,
  3
]
Expected
-1
Why
the route costs more fuel than all stations provide

Example 3

ready
Input
gas = [
  5,
  1,
  2,
  3,
  4
]
cost = [
  4,
  4,
  1,
  5,
  1
]
Expected
4
Why
index 4 is the only start whose tank never turns negative

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite