DrawCode Algorithm Visualizer • Greedy • Medium

Gas Station (Greedy)

Tags: Greedy, Circular, Prefix sum, Arrays, LeetCode

1. One-Liner

Gas Station tries each station as start in O(n) by tracking tank; if tank goes negative, discard all previous candidates and start fresh from the next index—works if total gas ≥ total cost.


2. The Problem It Solves

Circular road with gas[i] and cost[i] between stations. Find a starting index to complete one loop with tank never negative, or -1 if impossible.


3. The Core Idea

If cumulative balance from a to b fails, no station in [a,b] can be a valid start (you’d still hit the same deficit). So jump start to b+1. Total feasibility check: sum(gas) ≥ sum(cost).


4. How It Works (Step-by-Step)

StepWhat Happens
1. Total checkIf Σ gas < Σ cost, return -1
2. TankFrom start, add gas[i]-cost[i] each step
3. ResetIf tank < 0, set start = i+1, tank = 0
4. AnswerFinal start after one pass

5. Dry Run Example

gas=[1,2,3,4,5], cost=[3,4,5,1,2]. Total gas = cost = 15 → possible. Sweep finds unique valid start (classic example reasoning).


6. Key Properties

PropertyValue
Linear scanO(n)
UniquenessAt most one start if feasible

7. Where It Is Used

DomainUse
InterviewsCanonical greedy proof
CPCircular array tricks

8. Interview Tips

Prove failure segment can’t contain answer; mention two-pass or modulo indexing variant.


9. Comparison with Other Approaches

ApproachTime
Greedy sweepO(n)
Try all startsO()

10. Complexity

MetricValue
TimeO(n)
SpaceO(1)

Implementation Example (PYTHON)

def can_complete_circuit(gas, cost):
    if sum(gas) < sum(cost):
        return -1
    start = tank = 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:
            start = i + 1
            tank = 0
    return start

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer