mediumGreedyAmazonFacebook
Petrol Loop Picker
A tour organizer picks the only starting gas station from which the vehicle can complete the circular route.
Given gas[i] and cost[i] for each station, return the start index to complete one full clockwise trip, or -1 if impossible.
Choose approach
1
0i
2
1start
3
24
35
4Mapbalance
diff→-2
tank→0
total→-2
1/6
Narrationstep 1 of 6
i=0: gas-cost=-2, tank=0, total=-2 → reset start=1.
Variables
i=0
diff=-2
tank=0
total=-2
start=1
How to think about it
- sum(gas-cost) >= 0 is necessary and sufficient for feasibility.
- Reset trick skips all impossible starts in O(1).
Edge cases to catch in interview
- Deficit total -> -1.
- Single station with gas ≥ cost -> 0.
Examples
Example 1
-1{"gas":[2,3,4],"cost":[3,4,3],"values":[2,3,4]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed