LeetCode 134: Gas Station is a Medium array / string problem. This Python walkthrough develops a greedy restart solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Array / String |
| Reusable pattern | greedy restart |
| Complexity | O(n) time and O(1) extra space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, if total fuel is insufficient no start works. While scanning, a negative running tank invalidates every start since the previous candidate, so restart after it. The invariant worth writing beside the code is: The current candidate can reach every station processed since it was chosen.
Step-by-step algorithm
- Identify the input state consumed by
canCompleteCircuit(gas, cost)and initialize the data required by the greedy restart pattern. - If total fuel is insufficient no start works. While scanning, a negative running tank invalidates every start since the previous candidate, so restart after it.
- After each update, verify the page’s central invariant: The current candidate can reach every station processed since it was chosen.
- Finish only after the boundary behavior is covered: A valid start may be the final station; the total balance decides impossibility.
Python solution
class Solution:
def canCompleteCircuit(self, gas, cost):
if sum(gas) < sum(cost):
return -1
start = tank = 0
for i, (fuel, price) in enumerate(zip(gas, cost)):
tank += fuel - price
if tank < 0:
start, tank = i + 1, 0
return startReading the implementation
The main entry point is canCompleteCircuit(gas, cost). The named working state includes start, tank; those variables make the greedy restart state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, if total fuel is insufficient no start works. While scanning, a negative running tank invalidates every start since the previous candidate, so restart after it.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. If total fuel is insufficient no start works. While scanning, a negative running tank invalidates every start since the previous candidate, so restart after it. Each update records the current item without invalidating earlier decisions; consequently, the current candidate can reach every station processed since it was chosen.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().canCompleteCircuit([1,2,3,4,5],[3,4,5,1,2]) == 3Common mistakes and edge cases
- Problem-specific boundary: A valid start may be the final station; the total balance decides impossibility.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that the current candidate can reach every station processed since it was chosen.
Interview review checklist
- Explain why greedy restart matches the structure of this input.
- State the invariant in one sentence before tracing code: The current candidate can reach every station processed since it was chosen.
- Derive O(n) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: A valid start may be the final station; the total balance decides impossibility.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 238. Product of Array Except Self · Next: 135. Candy