Algo-Sim › Greedy
Gas Station
Medium · Greedy · step through it in Java, Python and C++ on your own input
Find the station to start from to drive the whole loop, or -1. When the tank goes negative, every start so far is ruled out at once.
Problem
Gas stations sit on a circular road. Station i gives you gas[i] units, and driving on to station i + 1 uses cost[i]. Starting with an empty tank, return the index of the station from which you can drive one full lap, or -1 if no start works. If a start exists, it is unique.
Constraints
- 1 ≤ n ≤ 10⁵ (n = gas.length = cost.length)
- 0 ≤ gas[i], cost[i] ≤ 10⁴
- If sum(gas) < sum(cost), the answer is −1
Edge cases to test
- Total gas < total cost:
-1 - One station
- The start is the last station
Follow-up questions
- Why can the start jump past every failed station?
- If you run dry at j starting from i, every start between i and j had a non-negative tank on arrival and would fail at j too.
- Why does a full loop work once total gas ≥ total cost?
- The deficit before the chosen start is covered by the surplus after it, because the totals balance: one O(n) pass.
Solution
Java
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0, tank = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
int diff = gas[i] - cost[i];
total += diff;
tank += diff;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total >= 0 ? start : -1;
}Python
def can_complete_circuit(gas, cost):
total = tank = start = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
tank += diff
if tank < 0:
start = i + 1
tank = 0
return start if total >= 0 else -1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int total = 0, tank = 0, start = 0;
for (int i = 0; i < int(gas.size()); i++) {
int diff = gas[i] - cost[i];
total += diff;
tank += diff;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total >= 0 ? start : -1;
}
};
More Greedy problems
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)