Update: 0001-two-sum.py - add improved two-pass solution#5945
Open
Darky321 wants to merge 1 commit into
Open
Conversation
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.
The NeetCode website shows a two-pass hash map solution for Two Sum, but it is not present in this repo. Additionally, the website's two-pass solution has a bug with duplicate numbers — for example, input of "nums = [2,3,3], target = 5" incorrectly returns [0,2] instead of [0,1] because it overwrites duplicate indices in the map.
NeetCode's test cases never went over this specific type of edge case, so the solution worked out. However the solution still breaks on test cases similar to the above input.
This PR adds a corrected two-pass solution that handles duplicates by storing all indices in a list and temporarily removing the current index before searching, avoiding false matches.
Note
Add two-pass hash map solution for two-sum in Python
Adds a second
Solutionclass implementing a two-pass approach to 0001-two-sum.py. The first pass builds a dict mapping each value to all its indices; the second pass looks up each complement while temporarily removing the current index to avoid self-pairing. Risk: because Python module semantics use the last class definition, the new two-passSolutionshadows the original one-pass implementation, and index ordering in returned pairs may differ.Macroscope summarized a346371.