There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique.
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3 Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.
Example 2:
Input: gas = [2,3,4], cost = [3,4,3] Output: -1 Explanation: You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start.
Constraints:
n == gas.length == cost.length1 <= n <= 1050 <= gas[i], cost[i] <= 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to figure out if you can drive a complete circle around a circular track with various fuel stops and distances between them. The brute force strategy involves testing every single stop as your potential starting point and simulating the entire journey around the track to see if you can make it back without running out of gas.
Here's how the algorithm would work step-by-step:
def can_complete_circuit(gas_amounts, cost_amounts):
total_stations = len(gas_amounts)
# Test every station as a starting point to cover all possible rotation paths
for start_station in range(total_stations):
current_fuel_tank = 0
current_station = start_station
steps_traveled = 0
while steps_traveled < total_stations:
current_fuel_tank += gas_amounts[current_station] - cost_amounts[current_station]
# Abort this starting point if fuel drops below zero during the trip
if current_fuel_tank < 0:
break
current_station = (current_station + 1) % total_stations
steps_traveled += 1
# Return the starting index if we successfully simulated a full circuit
if steps_traveled == total_stations and current_fuel_tank >= 0:
return start_station
return -1Instead of testing every single station as a starting point, we can use a clever shortcut that instantly rules out impossible starting points. By tracking our fuel levels as we travel in a single pass, we can guarantee a successful starting point if one exists.
Here's how the algorithm would work step-by-step:
def can_complete_circuit(gas_stations, cost_to_travel):
# We verify if total fuel is sufficient to guarantee at least one valid complete circuit exists.
if sum(gas_stations) < sum(cost_to_travel):
return -1
current_fuel_tank = 0
optimal_start_index = 0
for station_index in range(len(gas_stations)):
current_fuel_tank += gas_stations[station_index] - cost_to_travel[station_index]
# If fuel drops below zero, all stations up to this point are invalid starting candidates.
if current_fuel_tank < 0:
optimal_start_index = station_index + 1
current_fuel_tank = 0
# The remaining single candidate is guaranteed to be the correct starting station.
return optimal_start_index| Case | How to Handle |
|---|---|
| Total gas is strictly less than total cost | The greedy algorithm tracks the running total deficit and returns negative one since completion is mathematically impossible. |
| Single gas station where gas equals or exceeds cost | The loop initializes properly and returns index zero since zero gas is needed to travel nowhere on a single station loop. |
| Single gas station where gas is less than cost | The initial check fails and the algorithm correctly returns negative one because we cannot afford the trip to the next station. |
| Maximum sized arrays with up to one hundred thousand elements | A single pass linear scan runs in O of N time complexity and O of one auxiliary space ensuring optimal efficiency. |
| All gas values are zero while costs are positive | The accumulated tank drops below zero at the very first step and the start index resets until negative one is returned. |
| Valid starting station is at the very last index of the arrays | The algorithm resets the candidate starting index to zero when the tank goes negative and settles on the final index. |
| Multiple potential starting stations exist | Mathematical guarantees ensure that if a solution exists, it is unique, and the greedy approach will successfully find it. |
| Integer overflow during gas accumulation | Standard thirty two bit integers are sufficient because problem constraints keep cumulative sums within normal integer limits. |