DSA Tracker

Medium

Gas Station

A medium Greedy problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Greedy
Sheets
2
Core for
3 roles
Platform
LeetCode

The problem

There are gas stations along a circular route. Each station has some gas and it costs a certain amount to travel to the next station. Find the starting gas station index from which you can travel around the circuit once in the clockwise direction. If impossible, return -1.

Example 1

Input
gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output
3
Why
Starting at station 3, you can complete the full circuit.

Example 2

Input
gas = [2,3,4], cost = [3,4,3]
Output
-1
Why
No starting station allows completing the circuit.

Constraints

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

How to think about it

Updated 2026-09-09

If you start at station A and run out of gas at station B, no station between A and B could have made it either, because you arrived at each with non-negative fuel and still failed. The next candidate can only ever be B + 1.

Approaches, worst first

  1. Simulate from every station

    time O(n^2) · space O(1)

    Test each station as a candidate starting point, running the simulation until either the circuit completes or the tank dips below zero. Redundantly re-evaluates overlapping traversals after failures.

  2. Single pass accumulationWrite this one

    time O(n) · space O(1)

    Track total net gas and current tank balance. If current tank drops negative at i, reset candidate start to i + 1 and zero out the current tank. If total net gas across the entire circuit is non-negative, the candidate start is guaranteed to succeed.

Where people lose marks · 3
  • Looping around cyclically in the simulation without realizing total gas minus total cost determines overall feasibility in one pass.
  • Updating the candidate start index without resetting the current running tank balance to 0.
  • Returning the candidate start index when the sum of gas is strictly less than the sum of cost; no start can succeed if total gas is insufficient.

The theory behind it

Greedy — the ground this problem stands on. All Greedy problems

What Greedy is

A greedy algorithm makes the best-looking choice available right now, at every step, without ever looking back or second-guessing its decision. Think of a cashier making change by handing over the largest possible coin first, repeatedly, until the total is reached. Unlike dynamic programming, which saves and compares answers to multiple overlapping paths, a greedy strategy commits to one immediate option and keeps moving forward.

When to reach for it

Reach for greedy when problems ask for minimum jumps, interval scheduling, assigning resources to maximize satisfaction, or finding fractional values. Key signals include sorted orders where greedily taking the next item never hurts future options, or gas station round trips where running balances prove reachability. If you can prove that taking the immediate best choice never leaves you worse off than any alternative, greedy gives the fastest answer.

How the pattern works

Start by sorting the input to bring the most promising candidates to the front. At each position, evaluate your local rule, take the best available piece, and update your running state. The crucial mental step is proving the greedy choice property: demonstrate that picking this immediate winner cannot block a better global solution down the road. If choosing an item now forces you to reconsider past decisions when conditions change later, greedy fails and you must switch to dynamic programming instead.

What each operation costs

OperationTime
sort elements to enable greedy selectionO(n log n)
greedy single-pass scan through sorted inputO(n)
greedy choice using a priority queueO(n log n)
What usually goes wrong with Greedy
  • Applying a greedy choice without proving it yields the global optimum, such as picking the largest coin first for arbitrary denominations where dynamic programming was required.
  • Forgetting to sort the input before running the greedy loop, making local decisions on unordered elements that produce invalid answers.
  • Picking items based on only one attribute when the optimal decision depends on a ratio or combination of multiple attributes.

Which roles need this problem

Greedy is a core topic for these 3 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 4 more roles, including Site Reliability Engineer, Search Engineer, Quant Developer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Greedy problems

Problem set and role mapping as of .