def twoNumberSum(array, targetSum):
# Save the number seen so far
seen = set()
# Traverse the array
for n in array:
# Assume n is the first number
n2 = targetSum - n # Calcualte which is the other number needed
seen.add(n) # Keep track of all the seen numbers
if n2 != n and n2 in seen:
return [n, n2] # Found it
return []
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
required = {}
for i in range(len(nums)):
if target - nums[i] in required:
return [required[target - nums[i]], i]
else:
required[nums[i]] = i