Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created May 21, 2023 21:06
Show Gist options
  • Select an option

  • Save optimistiks/c3095d13c76a84731e3755b64bb7f5d5 to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/c3095d13c76a84731e3755b64bb7f5d5 to your computer and use it in GitHub Desktop.
Find the index of the gas station in the integer array gas such that if we start from that index we may return to the same index by traversing through all the elements, collecting gas[i] and consuming cost[i].
// gas is an array of numbers, where each number represents the amount of gas we can put in our car fuel tank on ith gas station.
// cost is how much gas we need to spend to move from gas station i to gas station i+1.
// we need to find an index of the gas station from which we can start our journey and visit every gas station.
export function gasStationJourney(gas, cost) {
// first, calculate total amount of gas in all gas stations
const totalGas = gas.reduce((acc, amount) => acc + amount, 0);
// second, calculate the gas cost of the whole journey
const totalCost = cost.reduce((acc, amount) => acc + amount, 0);
if (totalCost > totalGas) {
// if total gas cost is greater than the total amount of gas, the journey is not possible
return -1;
}
// otherwise we know that there is a solution
// initialize our result with gas station at index 0
let start = 0;
// current gas in our tank
let currGas = 0;
for (let i = 0; i < gas.length; ++i) {
// update our gas value, put in the amount of gas from the station i,
// and spend the amount of gas needed to travel to gas station i + 1
currGas = currGas + gas[i] - cost[i];
if (currGas < 0) {
// if at this point our gas amount is negative,
// it means it's not possible to complete our journey by starting from gas station at "start".
currGas = 0;
// the next possible result will be a gas station at i + 1
start = i + 1;
}
}
return start;
}
// O(n) time, O(1) space.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment