1. Feasibility sum
total sums every gas - cost; non-negative means a solution exists.
let total = 0Typorithm · medium
Step 1 of 8 · intro card
Greedy
Track total feasibility and a resettable running tank; the answer is where the tank last reset.
You can start at any station and must drive a full loop, gaining gas[i] and paying cost[i].
If the total gas is at least the total cost, exactly one valid start exists.
Whenever the running tank dips below zero, every station up to here fails, so the next station becomes the candidate start.
total >= 0 decides if any start works.
Reset start when tank < 0.
Single pass, no nested retries.
function canCompleteCircuit(gas, cost) {
let total = 0;
let tank = 0;
let start = 0;
for (let i = 0; i < gas.length; i += 1) {
const diff = gas[i] - cost[i];
total += diff;
tank += diff;
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return total >= 0 ? start : -1;
}Connect each part of the code to the concept before you type.
total sums every gas - cost; non-negative means a solution exists.
let total = 0tank is the fuel since the current candidate start.
let tank = 0The net fuel gained or lost at station i.
const diff = gas[i] - cost[i]If the tank goes negative, no start in [start..i] works; jump start to i + 1.
if (tank < 0)A valid start exists iff the overall total is non-negative.
return total >= 0 ? start : -1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputGas 1,2,3,4,5 · cost 3,4,5,1,2
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state