Repository navigation
fix(gas station): return -1 when no complete circuit exists - #304
Merged
Merged
Conversation
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Root cause
canCompleteCircuitreset 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])returned2, expected-1(total gas 9 < cost 10).canCompleteCircuit([1], [2])returned1, 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✅ Doneas 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.__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