50. Two sum
Write a function two_sum(numbers, target) that takes a list of whole numbers and a whole number target, and
returns the positions of the two numbers that add up to target, as a list [i, j] with i smaller than j.
- Positions are indexes, counting from 0.
- The two positions must be different: one item can't be used twice. Two equal numbers at different positions are
fine, as in
[5, 1, 5]with a target of 10. - Exactly one pair adds up to
targetin each list the tests give.
Checking every pair works, but takes about n * n / 2 steps. Can you do it in one pass through the list?
Example 1
numbers = [4, 9, 1, 6], target = 7[2, 3]Example 2
numbers = [5, 1, 5], target = 10[0, 2]Example 3
numbers = [1, 5, 9], target = 10[0, 2]Constraints
numbershas 2 to 1000 whole numbers, each from -1000 to 1000.targetis a whole number from -2000 to 2000.- Exactly one pair of positions has numbers that add up to
target.
Submit also runs 8 more tests you can't see.
Practises Dictionaries (lesson 11).
- For each number
x, the partner it needs istarget - x. The question is whether that partner came earlier in the list. - Keep a dictionary from each number seen so far to its index:
x in seenis one step, not a search through the list. - At index
j, check for the partner first and only then addseen[x] = j: adding it first would letxpair with itself whenx + x == target. Return[seen[partner], j].
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def two_sum(numbers, target):
"""Find the two numbers that add up to target.
numbers: list of int, with exactly one such pair
target: int, the sum to look for
Returns: list of two ints, [i, j], the pair's indexes,
with i < j
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.