Skip to main content

Gas Station

Given gas available and cost to travel, find starting station Return index of starting station, or -1 if impossible Example: gas=[1,2,3,4,5], cost=[3,4,5,1,2] => 3

Given equally sized, non-empty arrays of non-negative integers gas and cost, find a starting station for one complete clockwise trip around a circular route. At station i, collect gas[i] fuel and spend cost[i] to reach the next station, wrapping from the last station to station 0. The tank has unlimited capacity, starts empty at the chosen station, and its fuel must never become negative. Return the zero-based starting index, or -1 if no station allows a complete trip. If a valid starting station exists, it is unique.

Examples

You write

can_complete_circuit(gas: List[int], cost: List[int])

  1. Example 1

    Input
    gas=[1,2,3,4,5], cost=[3,4,5,1,2]
    returns
    3
  2. Example 2

    Input
    gas=[2,3,4], cost=[3,4,3]
    returns
    -1

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Greedy

I reach for it when

  • A locally best choice looks safe.
  • You sort first, then sweep once.

Say this before you type. Say the greedy choice, then say why swapping it for another choice cannot do better.

All 17 Greedy problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Gas Stationmedium

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.