Skip to content

Gas Station

MediumGreedy
Decode it first. Clues, constraints, pattern and plan before any code.

Gas stations sit on a circular road. Station i gives you gas[i] litres, and driving from station i to station i + 1 (wrapping around at the end) uses cost[i] litres. Your tank starts empty and has no limit. Return the index of the station where you can start and drive one full lap, or -1 if no start works. When an answer exists it is unique.

gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]  →  3
gas = [2, 3, 4],       cost = [3, 4, 3]        →  -1

Constraints

  • n == gas.length == cost.length
  • 1 <= n <= 10^5
  • 0 <= gas[i], cost[i] <= 10^4