Two Sum
Medium · 60 XPGiven a list and a target, return the indices of the two numbers summing to it — in one pass, not nested loops. Print the result for three cases.
Target output
[0, 1] [1, 2] []
Blank · autosaved
PYtwo-sum.py
Keep a dict of value→index as you go. For each number, check whether target - number is already in it.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
return []
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([3, 2, 4], 6))
print(two_sum([1, 2, 3], 99))
Run your code to check it…