CPKit
v1.6.1

Gas Station

GreedyMedium

Greedily identify start indexes completing circular path gas checks.

Alt+Shift+G

Configuration Panel

Gas Station Simulation Trace Logs

Simulation Running Steps:
Run simulation to audit logs.

Time Complexity

O(N) single sweep

Space Complexity

O(1) auxiliary variables
Conceptual Overview

The Gas Station problem finds the starting gas station's index from which you can travel around the circular circuit once in the clockwise direction without running out of gas, given gas levels and travel costs.

Greedy Choice Property

Verify if total gas >= total cost first. If yes, sweep stations from 0. Keep a running gas tank balance: if the tank drops below 0 at station i, the start station cannot be between the previous start and i. Reset the start station search to i + 1.

Optimal Substructure

A valid start index is guaranteed to exist and complete the circuit once we identify a start index j that maintains a positive running tank for the rest of the array scan.

Proof Idea / Correction

Proof by contradiction: if the tank goes negative at station i starting from j, no station between j and i can be a valid starting station because they would arrive at i with less than or equal gas.

Source: CP-Algorithms greedy reference