Gas Station

Medium#134reset the start

Gas stations stand on a circular road. Station k gives gas[k] units of fuel, and the road from it to the next station takes cost[k]. The car starts at some station with an empty tank. Find the station from which it can drive the whole circle, or return -1 if there is none; if there is one, it is the only one. Our example: gas [4, 3, 1, 5, 2, 4, 1], cost [2, 2, 5, 2, 3, 2, 3] — the answer is 3.

input
gas, cost: arrays of the same length. Stations stand on a circle; at station i the car fills up gas[i] units, and driving from it to the next station, i + 1 (after the last one, station 0), burns cost[i]. The tank has no limit.
returns
The index of the station to start from, with an empty tank, to drive once around the circle without running out of gas; -1 if there is none.
constraints
  • 1 ≤ gas.length ≤ 3000
  • cost.length == gas.length
  • 0 ≤ gas[i], cost[i] ≤ 10⁴
  • at most one station to start from
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} gas
 * @param {number[]} cost
 * @return {number}
 */
function canCompleteCircuit(gas, cost) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more greedy problems

Pattern “Greedy” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.