Two Sum

Find the two numbers in an array that add up to a target, and return their positions.

You are given an array of integers nums and a number target. Find two numbers in the array whose sum is target, and return their indexes, the positions where they sit in the array. The two numbers must come from two different positions. Each input has exactly one answer.

Example 1
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation: nums[1] + nums[2] = 2 + 4 = 6.
Example 2
Input: nums = [3, 3], target = 6
Output: [0, 1]
Solution

The Idea

Imagine a gift card worth 6 and a shelf with three items priced 3, 2 and 4. You want two different items that use up the card exactly. The 3 looks tempting, since 3 + 3 = 6, but there is only one item priced 3, and you cannot buy it twice. The 2 and the 4 work: 2 + 4 = 6. They are at positions 1 and 2, counting from 0, so the answer to Example 1 is [1, 2].

Example 2 is the same card with two items priced 3 each. Now 3 + 3 is fine, because the two 3s sit at different positions, 0 and 1.

The plain way to solve this is to try every pair of positions and check its sum. With three numbers there are only three pairs. With 10,000 numbers there are about 50 million. Is there a quicker way?

There is, because each number has only one possible partner, the number that completes the sum. If you hold a 4 and the target is 6, the other number must be 6 - 4 = 2. Nothing else works. So instead of trying every pair, you can ask a single question for each number: have I already passed the number it needs?

To answer that, walk through the array from left to right and write down each number you pass, together with its index. Call that note seen, and call the current index i. Look at the picture below.

Walking through nums = [3, 2, 4] with target 6. At i = 0 the 3 needs 3, which is not seen yet, so 3 is stored at index 0. At i = 1 the 2 needs 4, not seen, so 2 is stored at index 1. At i = 2 the 4 needs 2, which was seen at index 1, so the answer is [1, 2].

In the first row, i is 0 and the number is 3. It needs 6 - 3 = 3, but seen is still empty, so 3 is written down with index 0. Notice that the 3 does not match itself, because it is checked before it is written down. In the second row, 2 needs 4, which has not been seen either, so 2 is written down with index 1. In the last row, 4 needs 2, and seen has 2 at index 1. The answer is [1, 2].

So one pass is enough: every number looks back for its partner, and the note of numbers already passed makes that look quick.

Solution Approach

Turning that idea into code means settling three things: what holds the numbers already seen, the order of the check and the write, and what to return.

Storing the numbers already seen

What should seen be? It has to answer "is this value here, and at which index?" in one step, however many numbers it holds. A HashMap does that. It is Java's table from keys to values, and finding a key takes about the same time whether it holds ten entries or a million. Here each key is a number from the array, and its value is the index where that number sits.

A HashSet, which keeps only the numbers, would not be enough. It could say that the partner exists, but not where, and the answer needs positions.

Checking before writing down

Does it matter whether the current number is looked up first or written down first? It does. If the 3 in Example 1 were written into seen first, its own lookup for 3 would find it, and the method would return [0, 0], one item bought twice. Looking up first means seen only ever holds numbers at earlier positions.

Example 2 still works. The first 3 finds nothing and is written down with index 0. The second 3 then finds it there, so the answer is [0, 1].

What to return

What comes out when the partner is found? The partner was seen earlier, so its index comes first, then i. The problem promises an answer, but a method should still return something when there is none. Here it returns [-1, -1], which cannot be confused with real indexes.

Java Solution

The method twoSum works in these steps:

  1. First, create the map seen, a HashMap from each number already passed to its index. It starts empty.
  2. Walk through the array with one loop, where i is the current index.
  3. For each nums[i], look up its partner, target - nums[i], in seen, and keep what comes back in j. If j is not null, return [j, i].
  4. Otherwise, put nums[i] into seen with the index i, and move on to the next number.
  5. If the loop ends without a match, return [-1, -1].

The variable j is an Integer, not an int, because get returns null for a key that is missing. Index 0 is a real answer, so it could not serve as the "not found" signal.

The main method runs both examples, a pair at the very start of a longer array, a pair with a negative number, and an array where no two numbers reach the target.

Java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();   // value -> index where it was seen
        for (int i = 0; i < nums.length; i++) {
            Integer j = seen.get(target - nums[i]);     // the partner nums[i] needs
            if (j != null) {
                return new int[] {j, i};
            }
            seen.put(nums[i], i);
        }
        return new int[] {-1, -1};                      // no pair adds up to target
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[] {3, 2, 4}, 6)));
        System.out.println(Arrays.toString(twoSum(new int[] {3, 3}, 6)));
        System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(twoSum(new int[] {-3, 4, 3, 90}, 0)));
        System.out.println(Arrays.toString(twoSum(new int[] {1, 2, 3}, 7)));
    }
}

Running it prints:

Output
[1, 2]
[0, 1]
[0, 1]
[0, 2]
[-1, -1]

Look at the second line, [0, 1] from [3, 3]: the second 3 found the first one in seen, and the first 3 never matched itself. The third line, also [0, 1], comes from [2, 7, 11, 15] with target 9. The 7 finds the 2 straight away, so the loop stops before it reaches 11 and 15.

The fourth line, [0, 2], is -3 and 3 making 0. The 3 at index 2 needs 0 - 3 = -3, and negative keys work like any other. The last line, [-1, -1], is [1, 2, 3] with target 7: the largest possible sum is 2 + 3 = 5, so no pair exists.

The order of get and put is easy to swap by accident. A version that calls put first prints [0, 0] for Example 1, because the 3 at index 0 finds itself.

The original implementation, TwoSum.java, is on GitHub.

Complexity

The work is one pass over the array, with one map lookup and at most one map write per number.

  • Time: O(n), because the loop visits each of the n numbers at most once, and each get and put on the HashMap takes constant time on average.
  • Space: O(n). When the pair is the last two numbers, seen holds n - 1 entries before the match is found.

If the array is already sorted, two markers moving in from both ends find the pair without any map: see Two Sum II.