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.
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
}
}
O(N)
, where N
is the number of gas stations. We iterate through the array once.O(1)
, as we use only a constant amount of extra space.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.
For a detailed explanation, watch this video: Gas Station Problem Explanation by Shradha Khapra