Gas Station

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write startStation(gas, cost): n stations, from 1 to 100,000, stand in a circle. Station i gives you gas[i] fuel, and driving from it to the next, station i + 1 or station 0 after the last, uses cost[i]. Both are arrays of n whole numbers, none negative. The tank starts empty, holds any amount and must never go below 0. Return the index of the station to start from to drive once round the circle, or -1 if none works; when one works, it's the only one. Don't change the arrays. For example, with gas [1, 2, 3, 4, 5] and cost [3, 4, 5, 1, 2] the answer is 3. The checks include 100,000 stations, so trying every start is too slow.

Your code must pass

  • Finds the start in small examples
  • Returns -1 when there isn't enough fuel
  • Handles a single station
  • Is fast enough for 100,000 stations