The Logic
If we start at `A` and run out of gas before reaching `B`, it means NO station between `A` and `B` can be a valid starting point either! So our next potential start is `B+1`.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given a circular route with petrol pumps, find the starting pump from which the truck can complete the entire circle without running out of petrol.
If we start at `A` and run out of gas before reaching `B`, it means NO station between `A` and `B` can be a valid starting point either! So our next potential start is `B+1`.
This problem is often solved natively using a Queue by enqueuing and dequeuing stations. However, the optimized O(N) O(1) approach presented here conceptually slides a window over the route without actually needing queue memory.
We keep track of the gas deficit generated by failed starting points. At the very end, if the gas left in the tank covers the historical deficit, a tour is possible.