Gas Station

Find the starting gas station to complete a circular route.

Pattern

Circular Greedy

This problem follows the Circular Greedy pattern, commonly found in the Greedy category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

If total gas >= total cost, solution exists. Track running surplus; reset start when it goes negative.

Key Insight

If total gas >= total cost, a solution must exist. The greedy reset works because if you can't reach station i+1 from station j, you can't reach it from any station between j and i either.

Step-by-step

  1. 1If total gas < total cost, no solution exists
  2. 2Track running surplus (gas[i] - cost[i])
  3. 3When surplus goes negative, reset start to i+1 and reset surplus
  4. 4The final start position is the answer

Pseudocode

if sum(gas) < sum(cost): return -1
start = 0
surplus = 0
for i in range(len(gas)):
    surplus += gas[i] - cost[i]
    if surplus < 0:
        start = i + 1
        surplus = 0
return start
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Greedy Problems

Master this pattern with YeetCode

Practice Gas Station and similar Greedy problems with flashcards. Build pattern recognition through active recall.

Practice this problem