Problem
Ask
Submissions

Problem: Gas Stations

Medium
30 min
Explore how to apply greedy algorithms to determine the gas station index that allows completing a circular route. Learn to analyze the problem constraints and implement an efficient solution to decide if the journey is possible and identify the correct starting point if it exists.

Statement

There are nn gas stations along a circular route, where the amount of gas at the ithi^{th} station is gas[i].

We have a car with an unlimited gas tank, and it costs cost[i] of gas to travel from the ithi^{th} station to the next (i+1)th(i+1)^{th} station. We begin the journey with an empty tank at one of the gas stations.

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].

  • If it is not possible, return -1.

  • If there exists such index, it is guaranteed to be unique.

Constraints:

  • gas.length ==== cost.length
  • 1 \leq gas.length, cost.length 103\leq 10^3
  • 0 \leq gas[i], cost[i] 103\leq 10^3
Problem
Ask
Submissions

Problem: Gas Stations

Medium
30 min
Explore how to apply greedy algorithms to determine the gas station index that allows completing a circular route. Learn to analyze the problem constraints and implement an efficient solution to decide if the journey is possible and identify the correct starting point if it exists.

Statement

There are nn gas stations along a circular route, where the amount of gas at the ithi^{th} station is gas[i].

We have a car with an unlimited gas tank, and it costs cost[i] of gas to travel from the ithi^{th} station to the next (i+1)th(i+1)^{th} station. We begin the journey with an empty tank at one of the gas stations.

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].

  • If it is not possible, return -1.

  • If there exists such index, it is guaranteed to be unique.

Constraints:

  • gas.length ==== cost.length
  • 1 \leq gas.length, cost.length 103\leq 10^3
  • 0 \leq gas[i], cost[i] 103\leq 10^3