InterviewPrepKit

Home / Coding / Greedy

Gas Station

medium Original β†—
Solving tips
  • Feasibility first: a circuit is possible iff sum(gas) >= sum(cost); if not, return -1 immediately.
  • Greedy insight: sweep once tracking a running tank of gas[i]-cost[i]; when it dips below 0 at i, every start in [current_start, i] is doomed, so leap start to i+1 and reset tank to 0.
  • If the totals allow a solution, the last surviving candidate start completes the loop; O(n) time, O(1) space.
  • Pitfall: reset start to i+1 (not i, the station where you ran dry) and reset tank to 0, and don't skip the total-fuel feasibility check since the sweep returns an index unconditionally.

Problem

There are n gas stations arranged in a circle. Station i has gas[i] units of fuel, and it costs cost[i] units to drive from station i to the next station i+1 (wrapping from n-1 back to 0).

You start with an empty tank at some station and drive clockwise around the entire loop, filling up at each station before leaving. Return the index of the starting station from which you can complete the full circuit exactly once, or -1 if no such start exists. When a valid start exists, it is guaranteed to be unique.

Examples

  • gas = [1,2,3,4,5], cost = [3,4,5,1,2] β†’ 3 β€” starting at station 3: tank goes 4-1=3, then 3+5-2=6, then 6+1-3=4, 4+2-4=2, 2+3-5=0 β‰₯ 0 the whole way.
  • gas = [2,3,4], cost = [3,4,3] β†’ -1 β€” total gas 9 < total cost 10, so the loop is impossible from anywhere.
  • gas = [5,1,2,3,4], cost = [4,4,1,5,1] β†’ 4 β€” starting at station 4 keeps the tank non-negative around the circle.

Constraints

  • n == len(gas) == len(cost), 1 <= n <= 10^5
  • 0 <= gas[i], cost[i] <= 10^4

The 10^5 bound rules out the O(n^2) β€œtry every start” simulation; an O(n) single pass is expected.

Think about it first

Hint 1 First, a feasibility check that ignores where you start: compare the total fuel available with the total fuel needed. What must be true of sum(gas) versus sum(cost) for any circuit to be completable?
Hint 2 Track a running tank as you sweep left to right (no wrap yet). If the tank ever dips below zero at station i, your current start is doomed. But so is every station you passed through since that start β€” why?
Hint 3 When the tank goes negative at i, jump the candidate start to i+1 and reset the tank to 0. If the totals allow a solution at all, the last start you settle on is the answer.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.