The Gas Station Problem
July 17, 2015
Today’s exercise is a classic problem in computer science courses:
There is a truck driving clockwise on a circular route; the truck has a gas tank with infinite capacity, initially empty. Along the route are gas stations with varying amounts of gas available: you are given a list of gas stations with the amounts of gas they have available and the amounts of gas required to drive to the next gas station. You must find a gas station that, for a trip starting from that gas station, will be able to return to that gas station.
For instance, consider a route with eight gas stations having 15, 8, 2, 6, 18, 9, 21, and 30 gallons of gas; from each of those gas stations to the next requires 8, 6, 30, 9, 15, 21, 2, and 18 gallons of gas. Obviously, you can’t start your trip at the third gas station, with 2 gallons of gas, because getting to the next gas station requires 30 gallons of gas and you would run out of gas reaching it.
Your task is to write a program that determines a suitable starting point for the truck; your algorithm should be linear in the number of gas stations and require constant space. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
A brute force solution in Python.
And a better solution. Gives the same answer as the previous post.
Oops. Forget my last post. It is wrong.
Python solution:
Start at the first gas station.
If the gas in the tank plus the gas at the station is enough, then go to the next station (current += 1).
If there isn’t enough gas, then try moving the start gas station to the previous station (start -= 1).
Repeat until the truck makes it back to the start.
Only passes through the list of gas stations once and uses three variables, so it meets the O(n) time and O(1) space constraints.
Another Python solution. Take the cumulative sum of the excess fuel. The solution is the station after the station where the excess fuel is most negative.
Can Someone Name which classic problem is this..
Similar counting solution in SML:
This is much like Paul’s solution, ie. find the point with the smallest cumulative increase from the start, but written as single loop:
[…] Racket solution to the gas station problem: […]