Editor

Two Sum

#77 · Dictionaries and sets · Intermediate · 65 XP · about 10 min

Write two_sum(nums, target) that finds two different positions i and j in nums whose values add up to target, and returns them as a list [i, j] with i < j.

Exactly one pair of positions works. Two equal numbers at different positions can form the pair, but one position cannot be used twice.

Examples

two_sum([2, 7, 11, 15], 9)  # returns [0, 1]
two_sum([3, 2, 4], 6)       # returns [1, 2]
two_sum([5, 5], 10)         # returns [0, 1]

In the second example 3 + 3 would make 6, but there is only one 3, so the answer is the 2 and the 4.

Constraints

  • 2 <= len(nums) <= 10,000
  • Values and target are between -10**9 and 10**9
  • Exactly one pair of positions adds up to target

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.