Skip to content

44. Two Sum

Difficulty: Easy · Topic: DSA for data engineers

Write two_sum(nums, target): return a tuple (i, j) with i < j and nums[i] + nums[j] == target, or None if there is none. An element cannot be used twice.

If several pairs work, return the one with the smallest j, and for that j the smallest i. It must run in O(n): inputs can have 200,000 numbers.

Your code runs in CPython on our servers against 6 tests, including hidden ones.

Sample test

two_sum([2, 7, 11, 15], 9)

Expected: (0, 1)

Hints

Hint 1For each number, the partner it needs is target - x.
Hint 2Keep a dict from value to the first index where it was seen; look the partner up before adding the current number.
Hint 3Looking up before adding is what stops a number from pairing with itself.

Learn the concepts

More Python problems

All Python problems