Greedy Algorithms
Medium
Gas Station
Find the starting gas station to complete the circuit.
10 min read
Solve on LeetCodeProblem Understanding
There are n gas stations along a circular route. gas[i] is the gas at station i. cost[i] is cost to travel to i+1.
Return the index of the starting gas station if you can travel around the circuit once, otherwise return -1. Solution is unique if it exists.
Strategy
Greedy approach:
- Feasibility Check: If
sum(gas) < sum(cost), it's impossible. Return -1. - Find Start:
- Iterate through stations, accumulating
current_tank += gas[i] - cost[i]. - If
current_tank < 0, it means we cannot reach stationi+1from our currentstart. So, the start MUST be afteri. - Reset
current_tank = 0and setstart = i + 1.
- Iterate through stations, accumulating
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Complexity Analysis
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
