Write it, then count again
After this: Write the hash-map answer, do a dry run of it, and say its cost in time and memory.
On this page · 6 sections · 3 checks
You have a plan in words and a table that shows it working on [3, 2, 4]. Step 5 turns the plan into code, walks through it, and then counts its cost again, so that you can say how much faster it is.
The code
def two_sum(nums, target): seen = {} # value -> position for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return []
print(two_sum([3, 2, 4], 6))[1, 2]
import java.util.Arrays;import java.util.HashMap;
public class Main { static int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> seen = new HashMap<>(); // value -> position for (int i = 0; i < nums.length; i++) { int x = nums[i]; int need = target - x; if (seen.containsKey(need)) { return new int[] {seen.get(need), i}; } seen.put(x, i); } return new int[0]; }
public static void main(String[] args) { System.out.println(Arrays.toString(twoSum(new int[] {3, 2, 4}, 6))); }}[1, 2]
Line by line:
seenstarts as an empty map. Its keys will be numbers, and its values their positions.- The loop goes through the list once, with
ithe position andxthe number there. enumerate gives both at once.Java reads x from nums[i] on the next line. needis the partner x is waiting for: target − x.- The check line asks whether
needis already a key inseen. If it is, the function returns the stored position ofneed, then i. The stored one comes first, because it is the earlier position. - Otherwise, the store line puts x in the map with its position, for later numbers to find.
- If the loop ends with no match, no pair works, and the function returns the empty list.
A dry run
Walking through code by hand, one line at a time, with the values written down, is called a . In an interview you do it out loud, on the board or the screen. The trace band below does it for you; compare each step with the table from lesson 3.
- Run the programRun it and step through. Watch the box seen in the Variables panel, and the line that asks whether need is in it. Compare each step with the table in lesson 3.
def two_sum(nums, target): seen = {} # value -> position for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return []
print(two_sum([3, 2, 4], 6))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The box seen goes from {} to {3: 0} to {3: 0, 2: 1}. On the third number, need is 2, which is in the map at position 1, so the function returns [1, 2] and never stores the 4.
Count again
The loop visits each number once, and for each it does one lookup and at most one store. Each of those takes about one step. So the time cost is O(n), which means the work grows in step with the length of the list: double the list, and the work about doubles.
For 100,000 items, that is at most 100,000 lookups, where the brute force needed up to 4,999,950,000 pair checks.
There is a price. The map is : space the program sets aside on top of the input. In the worst case, when no pair works, every number ends up in the map, so the extra memory is O(n) too. The brute force needed no extra memory beyond a few variables.
| Answer | Time cost | Extra memory |
|---|---|---|
| Brute force: every pair | O(n²) | O(1), a few variables |
| Hash map: one pass | O(n) | O(n), the map |
This is the trade the tutorial set out to find: we spend memory to save time. It is one of the most common trades in interviews, and naming it out loud is part of the answer.
Run it
[2, 7, 11, 15] with target 9 finds its pair at position 1, after one lookup that misses and one that hits. Try the worst case from lesson 2, target 26, and count how many numbers are stored before the answer comes back.
Check yourself
Complete the line that asks whether the number we need has been seen already, so that the program prints [1, 2].
def two_sum(nums, target): seen = {} # value -> position for i, x in enumerate(nums): need = target - x ____________________ # ← is the number we need already in the map? return [seen[need], i] seen[x] = i return []
print(two_sum([3, 2, 4], 6))import java.util.Arrays;import java.util.HashMap;
public class Main { static int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> seen = new HashMap<>(); // value -> position for (int i = 0; i < nums.length; i++) { int x = nums[i]; int need = target - x; ____________________ // ← is the number we need already in the map? return new int[] {seen.get(need), i}; } seen.put(x, i); } return new int[0]; }
public static void main(String[] args) { System.out.println(Arrays.toString(twoSum(new int[] {3, 2, 4}, 6))); }}How much extra memory does the map version use on a list of n numbers, in the worst case?
The map version on [2, 7, 11, 15] with target 26. What does this print?
def two_sum(nums, target): seen = {} # value -> position for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return []
print(two_sum([2, 7, 11, 15], 26))import java.util.Arrays;import java.util.HashMap;
public class Main { static int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> seen = new HashMap<>(); // value -> position for (int i = 0; i < nums.length; i++) { int x = nums[i]; int need = target - x; if (seen.containsKey(need)) { return new int[] {seen.get(need), i}; } seen.put(x, i); } return new int[0]; }
public static void main(String[] args) { System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 26))); }}Honesty notes
- Write two sum with a hash map in Python or Java: work out need, check the map, return the stored position and the current one, otherwise store.
- Do a dry run of the code and follow the map as it fills.
- Say the cost: O(n) time on average and O(n) extra memory, against O(n²) time and no map for the brute force.
- Name the trade: the map spends memory to save time.