The Gas Station interview question is a classic problem involving a circular route. You have n gas stations, each providing a certain amount of gas[i]. Traveling to the next station costs cost[i] gas. You start with an empty tank. You need to find the starting gas station's index from which you can travel around the entire circuit once in a clockwise direction. If no such starting point exists, return -1. There is guaranteed to be at most one unique solution.
This is an extremely popular Greedy interview pattern problem asked by almost every major tech company, including Google, Amazon, and Meta. It tests a candidate's ability to optimize an brute-force check into an elegant single-pass solution. It evaluates mathematical intuition: realizing that if you fail to reach station starting from station , you will also fail starting from any station between and .
This problem relies on a Greedy Single-Pass pattern.
total_gas and total_cost. If total_gas < total_cost, it's mathematically impossible to complete the circuit, so return -1 immediately.current_tank and a potential start_index (initially 0).gas[i] - cost[i] to current_tank.current_tank < 0 at any point, it means you can't reach station from the current start_index.start_index = i + 1 and reset current_tank = 0.start_index.gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]
total_gas >= total_cost, which is the mathematical guarantee that the single-pass greedy logic will find a valid start.Memorize the proof for this greedy approach: If you start at A and your tank drops below zero just before reaching B, then starting at any station between A and B will drop below zero even earlier, because you would be starting with 0 gas instead of the positive gas you accumulated from A. Therefore, the next possible start is B.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Increasing Triplet Subsequence | Medium | Solve | |
| Maximum Distance in Arrays | Medium | Solve | |
| Minimum Domino Rotations For Equal Row | Medium | Solve | |
| Minimum Equal Sum of Two Arrays After Replacing Zeros | Medium | Solve | |
| Transform Array to All Equal Elements | Medium | Solve |