# Truck Tour HackerRank Solution

In this Truck Tour HackerRank solution, There is a circle. There are  petrol pumps on that circle. Petrol pumps are numbered  to  (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump.

Initially, we have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps. Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol.

## Truck Tour HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

### Problem Solution in Python

def truckTour(petrolpumps):
tank = startingIndex = 0

for i in range(len(petrolpumps)):
tank += petrolpumps[i][0]

if tank >= petrolpumps[i][1]:
tank -= petrolpumps[i][1]
else:
tank = 0
startingIndex = i + 1

return startingIndex

### Problem Solution in Go

func truckTour(petrolpumps [][]int32) int32 {
var gas,i int32
total := int32(len(petrolpumps))
n := total
for n > 0 {
gas += petrolpumps[i][0] - petrolpumps[i][1]
i = (i + 1) % total
n--
if gas < 0 {
n = total
gas = 0
}
}
// i will loop back to viable starting index when n == 0
return i
}

### Problem Solution in C++

int truckTour(vector<vector<int>> petrolpumps) {
int n = petrolpumps.size();
for (int i = 0; i < n; i++)
{
int petrol = 0;
int index = i;
if (petrolpumps[i][0] < petrolpumps[i][1])
continue;
while (true)
{
petrol += petrolpumps[index][0];
petrol -= petrolpumps[index][1];
if(petrol < 0)
break;
index = (index + 1)%n;
if(index == i)
break;
}
if (index == i)
return i;
}
return -1;
}

### Problem Solution in JavaScript

function truckTour(petrolpumps) {
let petrol = 0, distance = 0, first = 0;
for (let i=0; i<petrolpumps.length; i++){
petrol+=petrolpumps[i][0];
distance+=petrolpumps[i][1];
if (petrol<distance){
petrol=0, distance=0;
first=i+1;
}
}
return first;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems