Taro Logo

Gas Station

#1 Most AskedMedium
4 views
Topics:
ArraysGreedy Algorithms

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.length
  • 1 <= n <= 105
  • 0 <= gas[i], cost[i] <= 104
  • The input is generated such that the answer is unique.

Solution


Clarifying Questions

When 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:

  1. What should we return if multiple valid starting gas stations exist?
  2. Are the values in the `gas` and `cost` arrays guaranteed to be non-negative integers?
  3. What are the minimum and maximum lengths of the `gas` and `cost` arrays, and can the arrays be empty?
  4. Can the total amount of gas across all stations be less than the total cost required to traverse the entire circuit?
  5. If no complete circuit is possible, is returning `-1` always the correct expected output?

Brute Force Solution

Approach

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:

  1. Pick the very first gas station on the route as your starting point.
  2. Pretend to fill up your vehicle with the gas available at this station.
  3. Drive to the next station, using up some of your gas along the way.
  4. Check if you still have gas left in your tank to continue.
  5. If you run out of gas before making it all the way around the circle, this starting point fails.
  6. If you successfully make it back to your starting station, you have found a working solution.
  7. If the first station fails, go back to the beginning, pick the second gas station as your new starting point, and repeat the entire driving test.
  8. Continue this process of trying every single station one by one as the starting point until you either find one that works or exhaust all the stations.

Code Implementation

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 -1

Big(O) Analysis

Time Complexity
O(n²) – For each of the n gas stations in the array, the algorithm simulates a complete trip around the circular track visiting up to n stations. Testing the first station requires checking up to n steps, testing the second station requires up to n steps, and so on for all n possible starting points. This nested repetition of trying every starting point and simulating the full journey yields approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – The simulation strategy described only requires a few primitive scalar variables to track the current gas balance, the total accumulated fuel, and the starting index candidate. No auxiliary arrays, hash maps, or recursive call stacks are created during the nested loops. Regardless of the input size N representing the number of gas stations, the algorithm operates entirely in place using a constant amount of extra memory. Therefore, the auxiliary space complexity evaluates to a constant O(1).

Optimal Solution

Approach

Instead 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:

  1. First, check if the total amount of fuel available across all stops is at least equal to the total fuel needed to complete the entire circular route. If there is not enough fuel overall, it is impossible to complete the trip, so stop right there.
  2. Imagine driving around the circular route starting from the very first stop, keeping track of how much fuel you gain and burn at each stop.
  3. If your fuel tank ever dips below zero, it means you cannot reach the next stop using your current starting choice. Furthermore, you now know that every single stop you passed along the way is a terrible starting point because you failed to make it past your current position from any of them.
  4. Knowing this, completely wipe the slate clean, declare the stop immediately following your failure as your new hopeful starting point, and reset your fuel tank to zero.
  5. Continue driving forward and repeating this check until you have made it all the way around the entire route.
  6. The final hopeful starting point you settled on after checking the entire route is guaranteed to be the correct answer.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – To determine if a solution exists, we first iterate through all n gas stations to sum up the total gas and cost values. Next, we make a single pass through the array of size n to track our running fuel levels and identify the valid starting station. Rather than checking every station from scratch, resetting our start position allows us to visit each station a constant number of times. The total operations scale linearly with n as we make a constant number of passes over the input size, simplifying to O(n).
Space Complexity
O(1) – The algorithm only utilizes a few primitive scalar variables, such as total tank, current tank, and the starting index pointer, to track the fuel state during the single pass. Because no auxiliary data structures like temporary lists or hash maps are created, the extra memory required remains constant regardless of the input size N. Therefore, the auxiliary space complexity is O(1).

Edge Cases

Total gas is strictly less than total cost
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Mathematical guarantees ensure that if a solution exists, it is unique, and the greedy approach will successfully find it.
Integer overflow during gas accumulation
How to Handle:
Standard thirty two bit integers are sufficient because problem constraints keep cumulative sums within normal integer limits.
0/2 completed