Gas Station
MediumNeetCode 150Top Interview 150 GreedyInfosysScale AICME GroupBitGoSprinklrProblem
Stations sit on a ring road. Station i sells gas[i] units of fuel, and driving from
station i to the next one costs cost[i] units. Your tank has no size limit and starts empty.
Pick one station to begin at and drive around the ring in order, filling up at every station you pass.
Return the index of the starting station that lets you finish the full loop, or -1 if no start works.
When an answer exists it is unique.
Constraints
- 1 ≤ gas.length = cost.length ≤ 100000
- 0 ≤ gas[i], cost[i] ≤ 10000
- Every sum stays within ±10^9, so int is safe
Examples: pick one to animate
Solutions
Time: A single loop over the stations does constant work at each one.
Space: Only total, tank and start are kept.
Track the gain gas minus cost at each station. If the running tank goes below zero, no start up to this point can work, so restart right after it with an empty tank. If the total over all stations is not negative, the last restart is the answer.