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 numstargettarget
Example 1
Output: [1, 2]
Explanation: nums[1] + nums[2] = 2 + 4 = 6.
Example 2
Output: [0, 1]
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 seeni
In the first row, iseenseen[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 seenHashMap
A HashSet
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[0, 0]seen
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[-1, -1]
Java Solution
The method twoSum
- First, create the map
, aseen from each number already passed to its index. It starts empty.HashMap - Walk through the array with one loop, where
is the current index.i - For each
, look up its partner,nums[i] , intarget - nums[i] , and keep what comes back inseen . Ifj is notj , returnnull .[j, i] - Otherwise, put
intonums[i] with the indexseen , and move on to the next number.i - If the loop ends without a match, return
.[-1, -1]
The variable jIntegerintgetnull
The main
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:
[1, 2]
[0, 1]
[0, 1]
[0, 2]
[-1, -1]
Look at the second line, [0, 1][3, 3]seen[0, 1][2, 7, 11, 15]
The fourth line, [0, 2][-1, -1][1, 2, 3]
The order of getputput[0, 0]
The original implementation,
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
andget on theput takes constant time on average.HashMap - Space: O(n). When the pair is the last two numbers,
holds n - 1 entries before the match is found.seen
If the array is already sorted, two markers moving in from both ends find the pair without any map: see