Challenge: Two Sum
Completed
Read a list of numbers and a target. Print the positions (indexes, starting at 0) of the two numbers that add up to the target, smaller index first. There is exactly one answer. Aim for O(n) with a dictionary.
Input
Line 1: whole numbers. Line 2: the target.
Output
i j
Example
Input
2 7 11 15 9
Output
0 1
Editor
Python
Hints
For each number x, the partner you need is target - x.
Store number -> index in a dict as you go.
Solution explanation
One pass; each lookup in the dictionary is O(1), so the total is O(n).
Show solution
nums = list(map(int, input().split()))
target = int(input())
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
print(seen[target - x], i)
break
seen[x] = i Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module