← Whiteboard questions

Two Sum

Find two numbers that add up to a target

DSA, Easy, Arrays & Hashing

Which structure or algorithm, and what does it cost.

You get a list of integers nums and an integer target. Return the positions [i, j] of two different elements whose values add up to target. If no such pair exists, return []. If several pairs exist, return any one. You may not use the same position twice, but two equal values at different positions are allowed.

Examples

Input nums = [5, 12, 8, 3], target = 11
Output [2, 3]
Why because 8 + 3 = 11, and no other pair adds up to 11.
Input nums = [7, 7, 2], target = 14
Output [0, 1]
Why the two 7s sit at different positions, so both may be used.
Input nums = [6, 1, 5], target = 12
Output []
Why 6 + 6 would use position 0 twice, so there is no pair.

Constraints

Your answer must contain

Target Aim for O(n) time and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Fix one number x. What value would you need to find next to reach the target? Ask that before you think about speed.

Hint 2 the approach

Checking every pair works but is slow for 100,000 items. Remember what you have already seen, so each lookup costs one step instead of a scan.

Hint 3 the key step

Walk the list once, keeping a table from value to position. Look up the number you need before you store the current one.

Walkthrough

Full walkthrough brute force to best

Brute force

Test every pair of positions and return the first pair that adds up to the target. This is simple and always right. It takes O(n^2) time and O(1) memory. With 100,000 items that is about 5 billion pair tests, which is too slow.

Better method

Sort a copy of the list together with the original positions. Then move two pointers inward from both ends. If the sum is too small, move the left pointer right. If it is too big, move the right pointer left. The sort makes this O(n log n) time.

Best method

Use a hash map lookup. For each number x, the partner you need is exactly target - x. Keep a table from each value seen so far to its position. At each step, look up target - x first. If it is in the table, the stored position and the current position are the answer. If not, store x and move on. Looking up before storing means one position is never used twice. A pair whose partner comes later is still found, because the earlier number is already in the table when the partner arrives. The same idea fits any problem that asks whether the partner of an item has been seen: trade a little memory for a one-step lookup instead of a scan.

Hand trace

Run on nums = [5, 12, 8, 3] with target 11. Position 0, value 5: the partner is 6, the table is empty, so store 5 at position 0. Position 1, value 12: the partner is -1, not in the table, so store 12 at position 1. Position 2, value 8: the partner is 3, not in the table, so store 8 at position 2. Position 3, value 3: the partner is 8, found at position 2, so return [2, 3].

Code

def two_sum(nums, target):
    seen = {}                      # value -> position
    for i, x in enumerate(nums):
        j = seen.get(target - x)
        if j is not None:
            return [j, i]
        seen[x] = i
    return []

Time and memory

O(n) time, because one pass does a table step that costs O(1) on average. O(n) memory for the table in the worst case.

Common mistakes

  • Storing the number before looking up its partner. With target 6 and nums [3], this returns [0, 0], the same position twice.
  • Keeping values instead of positions in the table. The task asks for positions.
  • Skipping the lookup for a number whose value is already in the table. Equal values at different positions can form a pair. Not storing the second copy is fine.

Related problems

More Arrays & Hashing problems
Two Sum: hints, walkthrough and Python solution