Skip to content

Update: 0001-two-sum.py - add improved two-pass solution#5945

Open
Darky321 wants to merge 1 commit into
neetcode-gh:mainfrom
Darky321:main
Open

Update: 0001-two-sum.py - add improved two-pass solution#5945
Darky321 wants to merge 1 commit into
neetcode-gh:mainfrom
Darky321:main

Conversation

@Darky321

@Darky321 Darky321 commented Jun 30, 2026

Copy link
Copy Markdown

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 Solution class 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-pass Solution shadows the original one-pass implementation, and index ordering in returned pairs may differ.

Macroscope summarized a346371.

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.

1 participant