Builds onBig-O and complexity
01The idea
A hash map stores pairs of a key and a value. You look up a key, and the map returns its value. On average a lookup takes the same time whether the map holds ten pairs or ten million. We write that as O(1) on average.
A list cannot answer "is 9 in here?" that fast. You check its items one by one, and that takes O(n) time.
Many problems repeat one lookup for every item: did this value appear earlier? If each lookup costs O(n), the whole solution costs O(n²). If you put the items you have passed into a hash map, each lookup costs O(1). The whole solution then costs O(n).
The loop does two things for each item:
- Look up the item in the map.
- Store the item in the map, so later items can look it up.
Look up first, then store. If you store first, the lookup returns the current item, and every item looks like a repeat.
The key you look up does not have to be the item itself. You can look up any key you compute from the item.
02How to spot it
Use a hash map when the problem:
- asks whether a value appeared earlier, or how many times it appeared
- needs a pair of items that fit together, such as a fixed sum or difference, and the brute force checks every pair
- wants the positions of something, which you can store as the value
- groups items that share a property, such as words made of the same letters
The strongest signal is a brute force with two nested loops where the inner loop checks the earlier items for one value. The map replaces that inner loop.
03Worked example
Find the first repeat in a list. The first repeat is the earliest position whose value already appeared before it. Return the index where that value first appeared and the index of the repeat.
The input is nums = [4, 9, 2, 7, 9, 2].
We keep a map called seen. Each key is a number. Its value is the index where we first saw that number.
| Step | i | num | Is num in seen? | What we do | seen after the step |
|---|---|---|---|---|---|
| 1 | 0 | 4 | no | store 4 with index 0 | {4: 0} |
| 2 | 1 | 9 | no | store 9 with index 1 | {4: 0, 9: 1} |
| 3 | 2 | 2 | no | store 2 with index 2 | {4: 0, 9: 1, 2: 2} |
| 4 | 3 | 7 | no | store 7 with index 3 | {4: 0, 9: 1, 2: 2, 7: 3} |
| 5 | 4 | 9 | yes, at index 1 | return [1, 4] | no change |
The answer is [1, 4]. The loop stops at index 4, so it never reaches the second 2 at index 5.
Now picture a list in place of the map. At step 4 the list checks all three earlier items to learn that 7 is new. Every step checks every earlier item, so a long input costs O(n²) work.
The same loop works when the key comes from a calculation. Say you want two numbers that differ by exactly 3, and the current number is 8. Look up 5 and 11. If either one is in the map, you have a pair. Then store 8, as before.
04Watch it run
The worked example, step by step, with the code line that runs.
05Complexity
Time is O(n). The loop visits each item once. Each lookup and each store takes O(1) on average.
Space is O(n). In the worst case every item goes into the map before the loop ends.
The words "on average" matter. When many keys land in the same internal bucket, a lookup slows down. The hash maps in Python and Java make this rare, so in an interview you can count each lookup as O(1).
06Common mistakes
- Storing before the lookup. The lookup then returns the current item, and you report a repeat that is not there.
- Storing the wrong value. If the problem wants indices, store the index, not a count or a flag.
- Overwriting the first index. On a later copy,
seen[num] = ireplaces the earlier index. This example returns at the first repeat, so it cannot happen here. In problems that keep going, decide whether you want the first index or the latest one. - Using a list as a key. Python cannot hash a list. Turn it into a tuple or a string first.
- Using a map when an array is enough. If the keys come from a small fixed range, such as the 26 lowercase letters, an array of 26 counts is simpler and faster.
07Code template
def first_repeat(nums):
seen = {} # each number we have passed, with the index where we first saw it
for i, num in enumerate(nums):
if num in seen: # O(1) on average
return [seen[num], i]
seen[num] = i
return []
if __name__ == "__main__":
print(first_repeat([4, 9, 2, 7, 9, 2]))
print(first_repeat([1, 2, 3]))
import java.util.*;
public class Solution {
static int[] firstRepeat(int[] nums) {
Map<Integer, Integer> seen = new HashMap<>(); // each number we have passed, with the index where we first saw it
for (int i = 0; i < nums.length; i++) {
if (seen.containsKey(nums[i])) { // O(1) on average
return new int[]{seen.get(nums[i]), i};
}
seen.put(nums[i], i);
}
return new int[0];
}
public static void main(String[] args) {
System.out.println(Arrays.toString(firstRepeat(new int[]{4, 9, 2, 7, 9, 2})));
System.out.println(Arrays.toString(firstRepeat(new int[]{1, 2, 3})));
}
}
08Check yourself
Get every answer right to mark this lesson as done in all your study plans.
Your result is saved and marks this lesson as done in your study plans.