โ† Back to Index

๐Ÿ“š Gas Station โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Gas Station problem involves finding the starting gas station index from which you can complete a circular route around all gas stations. Each station provides a certain amount of gas, and you need a certain amount of gas to travel to the next station.

๐Ÿงฑ Pattern Template

Greedy Algorithm

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int totalGas = 0, totalCost = 0, startIndex = 0, currentTank = 0;

        for (int i = 0; i < gas.length; i++) {
            totalGas += gas[i];
            totalCost += cost[i];
            currentTank += gas[i] - cost[i];

            if (currentTank < 0) {
                startIndex = i + 1; // Reset starting point
                currentTank = 0;   // Reset current tank
            }
        }

        return totalGas >= totalCost ? startIndex : -1; // Check if a solution exists
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3

Explanation:
- Start at station 3 (0-based index).
- Travel around the circuit and return to station 3 with a non-negative tank.

๐Ÿ’ก Pro Tips

๐ŸŽฅ Video Explanation

For a detailed explanation, watch this video: Gas Station Problem Explanation by Shradha Khapra