Gas Station
Medium greedy · arrays
Description
Constraints
1 <= n <= 100000
Examples
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Hints (1)
- If total gas is less than total cost there is no answer; otherwise reset the start when the tank goes negative.
Solutions
Single pass with reset. · Time O(n) · Space O(1)
func canCompleteCircuit(gas, cost []int) int {
total, tank, start := 0, 0, 0
for i := range gas {
diff := gas[i] - cost[i]
total += diff
tank += diff
if tank < 0 {
start = i + 1
tank = 0
}
}
if total >= 0 {
return start
}
return -1
}
Single pass with reset. · Time O(n) · Space O(1)
function canCompleteCircuit(gas, cost) {
let total = 0, tank = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const diff = gas[i] - cost[i];
total += diff; tank += diff;
if (tank < 0) { start = i + 1; tank = 0; }
}
return total >= 0 ? start : -1;
}
Single pass with reset. · Time O(n) · Space O(1)
function canCompleteCircuit($gas, $cost) {
$total = 0; $tank = 0; $start = 0;
for ($i = 0; $i < count($gas); $i++) {
$diff = $gas[$i] - $cost[$i];
$total += $diff; $tank += $diff;
if ($tank < 0) { $start = $i + 1; $tank = 0; }
}
return $total >= 0 ? $start : -1;
}
Single pass with reset. · Time O(n) · Space O(1)
def canCompleteCircuit(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 -1
Single pass with reset. · Time O(n) · Space O(1)
function canCompleteCircuit(gas: number[], cost: number[]): number {
let total = 0, tank = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const diff = gas[i] - cost[i];
total += diff; tank += diff;
if (tank < 0) { start = i + 1; tank = 0; }
}
return total >= 0 ? start : -1;
}
Create a free account to submit solutions, track progress and save problems.
Create account