FastPrepGas Station

Gas Station

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

There are n gas stations on a circular route. gas[i] is the fuel available at station i, and cost[i] is the fuel needed to travel from station i to station (i + 1) mod n.

You start with an empty tank. Return the index of the station from which you can travel clockwise around the circuit exactly once without the tank becoming negative. Return -1 if no such station exists. If a solution exists, it is unique.

Function

canCompleteCircuit(gas: int[], cost: int[]) → int

Examples

Example 1

gas = [1,2,3,4,5]cost = [3,4,5,1,2]return = 3

Starting at station 3, the tank never becomes negative and returns to station 3 after visiting every station.

Example 2

gas = [2,3,4]cost = [3,4,3]return = -1

Total available fuel is less than the total travel cost, so no start can complete the circuit.

Example 3

gas = [5]cost = [4]return = 0

The single station supplies enough fuel for its only leg.

Constraints

  • 1 <= n == gas.length == cost.length <= 100000.
  • 0 <= gas[i], cost[i] <= 10000.
  • If a valid starting station exists, it is unique.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int canCompleteCircuit(int[] gas, int[] cost) {
    // Write your code here.
}
gas[1,2,3,4,5]
cost[3,4,5,1,2]
expected3
Checking account…