From a3463715de9993b8743b399a0b9add0e4a66e882 Mon Sep 17 00:00:00 2001 From: Vibhav Pata <137221624+Darky321@users.noreply.github.com> Date: Tue, 30 Jun 2026 12:52:51 -0700 Subject: [PATCH] Update: 0001-two-sum.py - add improved two-pass solution --- python/0001-two-sum.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/python/0001-two-sum.py b/python/0001-two-sum.py index e3eb994d3..17866537b 100644 --- a/python/0001-two-sum.py +++ b/python/0001-two-sum.py @@ -1,3 +1,4 @@ +# Hash Map (One Pass) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: prevMap = {} # val -> index @@ -7,3 +8,25 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: if diff in prevMap: return [prevMap[diff], i] prevMap[n] = i + + +# Hash Map (Two Pass) +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + indices = {} # val -> index + + for i, n in enumerate(nums): + indices.setdefault(n, []).append(i) + + for i, n in enumerate(nums): + diff = target - n + + # Temporarily pop current num "n" from map + indices[n].remove(i) + result = indices.get(diff, []) + if result: + return [i, result[0]] + + # If diff not found, add current num "n" back to map + indices[n].append(i) +