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
defmodule Solution dodef can_complete_circuit(_gas, _cost) do# Write your code hereendend
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
iifgas[i] - cost[i] < 0, because then there is not enough gas in the tank to travel to thei + 1station. Let’s say we have acurr_tankvariable that keeps track of the current amount of gas in the tank. If at a stationcurr_tankis less than0, this means that we cannot reach this station. Then, we need to mark this station as a new starting point and resetcurr_tankto0since, 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_tankandcurr_tankvariables as zero. We also choose station0as a starting station. - Iterate over all the stations:
- Update
total_tankandcurr_tankat each step, by addinggas[i]and subtractingcost[i]. - If
curr_tankis less than0at thei + 1station, we will makei + 1station a new starting point and resetcurr_tankto0to start with an empty tank.
- Update
- Finally, we will return
-1iftotal_tank < 0or 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 ...