The problem

You get a list of whole numbers and a target number. Find the two positions whose numbers add up to the target, and return those two positions. There is always exactly one answer, and you cannot use the same position twice.

Example: numbers [3, 9, 4, 7], target 11 → answer [2, 3], because 4 + 7 = 11.

What matters: the list can have up to 10,000 numbers, and numbers can be negative. The real question is: can you do better than checking every pair? (on LeetCode)

Think about

  • Checking every pair works. For 10,000 numbers, about how many pairs is that?
  • When you stand on a number x, you already know exactly which other value would complete the answer. Which value?
  • What data structure answers “have I already seen this value, and where?” instantly?

Solution