Gas Station
Understand and solve the interview question "Gas Station".
We'll cover the following...
Description
Suppose there are n
gas stations identified by integers 0, 1, . . ., n-1
, where the amount of gas at the station is gas[i]
. Imagine that these gas stations are arranged clockwise in a circle, as shown below.
You have a car with an unlimited gas tank. It costs cost[i]
amount of gas to travel from the station to the station. The trip will begin with an empty tank at one of the gas stations.
Given two integer arrays, gas
and cost
, you have to return the starting gas station’s index if you can travel around a circular route in the clockwise direction, otherwise, return -1
.
If a solution exists, it is guaranteed to be unique.
Let’s review a few examples below:
Coding exercise
fn can_complete_circuit(gas: Vec<i32>, cost: Vec<i32>)-> i32 {// write your code herereturn 0;}
Solution
Before getting to the solution, let’s discuss a couple of things:
-
We cannot perform the road trip if
sum(gas) < sum(cost)
. In this situation, the answer will be-1
. We can compute the total amount of gas in the tank,total_tank = sum(gas) - sum(cost)
, during the round trip. The round trip is only possible iftotal_tank >= 0
, otherwise we return-1
. -
We cannot start the trip at a station
i
ifgas[i] - cost[i] < 0
, because then there is not enough gas in the tank to travel to thei + 1
station. Let’s say we have acurr_tank
variable that keeps track of the current amount of gas in the tank. If at a stationcurr_tank
is less than0
, this means that we cannot reach this station. Then, we need to mark this station as a new starting point and resetcurr_tank
to0
since, at this station, we start with no gas in the tank.
The following illustration shows these steps in detail:
Algorithm
The algorithm to solve this problem is as follows:
- We initialize the
total_tank
andcurr_tank
variables as zero. We also choose station0
as a starting station. - Iterate over all the stations:
- Update
total_tank
andcurr_tank
at each step, by addinggas[i]
and subtractingcost[i]
. - If
curr_tank
is less than0
at thei + 1
station, we will makei + 1
station a new starting point and resetcurr_tank
to0
to start with an empty tank.
- Update
- Finally, we will return
-1
iftotal_tank < 0
or the starting gas station’s index otherwise.
Solution intuition
Suppose we have a situation where total_tank >= 0
and the algorithm above returns as the starting station. Our algorithm ensures that we can reach station 0
from . But what about going from station 0
to ? We need to ensure that we can loop around to .
Let’s use proof by contradiction and assume that there exists a station ...