#134

Gas Station

Medium Reset start on deficit

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Stations form a circle. You get gas[i] at station i and spend cost[i] to reach the next. Return the starting station that lets you go all the way around once, or -1. The answer is unique if it exists.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: from which station can you drive the full circle?

Why this works: if you run out between start and i, none of those stations can work either, so restart at i + 1. If total gas ≥ total cost, the last start works.

Example: gas [1,2,3,4,5], cost [3,4,5,1,2]

tank goes negative at 0, 1, 2 → restart at 3from 3: +3, +3, … total ≥ 0 → answer 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Simulating a full loop from every station — O(n²).

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Greedy
🎬 Episodes 69–73: video coming soon