Gas Stations


Gas Station – LeetCode


Problem: Gas Station

Problem Statement

There are n gas stations arranged in a circle. You are given two integer arrays gas and cost, where:

Given these two arrays, return the starting gas station's index from which you can travel around the circuit once in the clockwise direction. If it is not possible, return -1.


Examples

Example 1
Input:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (gas = 4),

Example 2
Input:
gas = [2,3,4]
cost = [3,4,3]
Output: -1
Explanation: It's not possible to complete the circuit from any station.


Constraints


Intuition

To successfully complete the circuit, the total amount of gas across all stations must be greater than or equal to the total cost to travel the entire loop. If this condition fails, return -1.

If the condition passes, then the problem reduces to finding the right starting station. We simulate the journey and track the current tank balance. If at any point this balance goes negative, the journey from the current start is not possible, and we move the start to the next station.


Approach

  1. Compute the total gas and total cost. If total gas < total cost, return -1.

  2. Initialize:

    • total = 0 → represents current net gas while simulating trip.

    • start = 0 → index of current candidate starting station.

  3. Traverse each station i from 0 to n-1:

    • Update total += gas[i] - cost[i].

    • If total < 0, it means we can't reach the next station:

      • Set start = i + 1.

      • Reset total = 0.

  4. After traversal, return start.


Code (Java)

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int tGas = 0;
        int tCost = 0;
        int n = gas.length;

        // Step 1: Check if solution exists
        for (int i = 0; i < n; i++) {
            tGas += gas[i];
            tCost += cost[i];
        }
        if (tGas < tCost) return -1;

        // Step 2: Find the correct starting point
        int total = 0;
        int start = 0;
        for (int i = 0; i < n; i++) {
            total += gas[i] - cost[i];
            if (total < 0) {
                total = 0;
                start = i + 1;
            }
        }

        return start;
    }
}

Time and Space Complexity


Dry Run

Input:

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

Simulation:


Conclusion

This problem is an excellent example of a greedy strategy combined with a feasibility check. Once it's confirmed that a complete loop is possible, identifying the correct starting point is simply a matter of restarting when the tank balance drops below zero.