Skip to content

fix(gas station): return -1 when no complete circuit exists - #304

Merged
Huerte merged 1 commit into
Huerte:mainfrom
bfs2021:fix/gas-station-total-check
Nov 18, 2026
Merged

Huerte merged 1 commit into
Huerte:mainfrom
bfs2021:fix/gas-station-total-check

Conversation

@bfs2021

@bfs2021 bfs2021 commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Root cause

canCompleteCircuit reset the greedy start index on deficit but never checked whether total gas covers total cost. When it doesn't, the function returned an arbitrary index instead of -1. The file header even named this: "forgets to verify if total gas covers total cost."

Repro: canCompleteCircuit([2,3,4], [3,4,3]) returned 2, expected -1 (total gas 9 < cost 10). canCompleteCircuit([1], [2]) returned 1, expected -1.

Fix

One guard after the greedy scan: if sum(gas) < sum(cost): return -1 (solutions/python/practice414.py, 3 added lines). Flipped status to ✅ Done as the issue asked and corrected the note. Valid circuits (including total-zero cases with a valid start) are unchanged.

Tests

Added tests/test_practice414.py (unittest, no deps) with 5 cases: valid circuit, impossible circuit, single impossible station, total-zero valid circuits, all-stations-valid.

  • Before: 2 failed / 3 passed.
  • After: 5 passed.
  • Original __main__ assertions still pass; standalone repro script 7/7.

Note on diff budget

Source diff 7+/2−; 33-line test file. Total 42 insertions / 2 deletions. Test code is pure standard-library unittest.

Per CONTRIBUTING I claimed the issue with a comment before starting. Fixes #292

@Huerte
Huerte merged commit 43dabbd into Huerte:main Nov 18, 2026
1 check passed
@github-actions

Copy link
Copy Markdown
Contributor

@bfs2021 thank you for your first contribution! Appreciated a lot.

Your avatar is now in the contributors section. The README updates automatically after every merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix and complete the Gas Station solution (practice414.py)

2 participants