Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions python/0001-two-sum.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# Hash Map (One Pass)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
prevMap = {} # val -> index
Expand All @@ -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)