14. Gas Station
β GFG solution to the Gas Station problem: find the starting station to complete a circular tour using greedy approach with optimal time and space complexity. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given two integer arrays gas[]
and cost[]
representing n gas stations along a circular tour. At station i
, you can fill gas[i]
units of gas and need cost[i]
units to travel to the next station (i+1)
. Starting with an empty tank, find the index of the starting station that allows you to complete the entire circular tour without running out of gas. Return -1
if no such starting station exists.
Note: If a solution exists, it is guaranteed to be unique.
π Examples
Example 1
Input: gas[] = [4, 5, 7, 4], cost[] = [6, 6, 3, 5]
Output: 2
Explanation: Start at station 2 with 7 units of gas. Tank = 0 + 7 = 7
Travel to station 3: Available gas = (7 - 3 + 4) = 8
Travel to station 0: Available gas = (8 - 5 + 4) = 7
Travel to station 1: Available gas = (7 - 6 + 5) = 6
Return to station 2: Available gas = (6 - 6) = 0
Example 2
Input: gas[] = [3, 9], cost[] = [7, 6]
Output: -1
Explanation: No starting station allows completing the circular tour.
Total gas = 3 + 9 = 12, Total cost = 7 + 6 = 13. Since total cost > total gas,
it's impossible to complete the tour.
π Constraints
$1 \le n \le 10^6$
$1 \le gas[i], cost[i] \le 10^3$
β
My Approach
The optimal solution uses a Greedy Algorithm that makes locally optimal choices to find the globally optimal starting station:
Greedy Single-Pass Algorithm
Key Insight:
If total gas β₯ total cost, a solution exists (guaranteed unique)
We need to find the optimal starting point using greedy selection
Algorithm Steps:
Track
total
: sum of all (gas[i] - cost[i]) differencesTrack
curr
: running balance from current potential startTrack
start
: current candidate starting station
Greedy Decision:
When
curr < 0
, the current starting point is invalidReset start to next station and reset current balance to 0
This works because if we can't reach station
i
from any station β€ j, then stationj+1
is the earliest possible valid start
Validation:
If
total β₯ 0
, return the found starting stationIf
total < 0
, no solution exists
Why This Works:
The greedy approach is optimal because:
If we can't complete the tour starting from station
i
, then starting from any station betweeni
and the failure point is also impossibleThe first station after a failure point is the next best candidate
Total gas vs total cost determines overall feasibility
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the number of gas stations. We traverse the array exactly once, performing constant operations at each station.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for tracking variables (total, curr, start) regardless of input size.
π§βπ» Code (C++)
class Solution {
public:
int startStation(vector<int>& gas, vector<int>& cost) {
int total = 0, curr = 0, start = 0;
for (int i = 0; i < gas.size(); i++) {
int diff = gas[i] - cost[i];
total += diff;
curr += diff;
if (curr < 0) start = i + 1, curr = 0;
}
return total >= 0 ? start : -1;
}
};
π§βπ» Code (Java)
class Solution {
public int startStation(int[] gas, int[] cost) {
int total = 0, curr = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
int diff = gas[i] - cost[i];
total += diff;
curr += diff;
if (curr < 0) { start = i + 1; curr = 0; }
}
return total >= 0 ? start : -1;
}
}
π Code (Python)
class Solution:
def startStation(self, gas, cost):
total = curr = start = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
curr += diff
if curr < 0: start, curr = i + 1, 0
return start if total >= 0 else -1
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated