Hash Map Patterns
Hash map patterns: complements, counts and canonical keys that turn a search inside a loop into one lookup, and the array used as its own hash map.
Hash map patterns keep a map of the items already seen, so the question each item asks about the earlier ones, whether its partner came before, how many of it there are, which group it belongs to, is answered by one lookup instead of a search. It matters because a search inside a loop is the most common bottleneck in a first solution, and removing it turns O(n²) into O(n) on average. The topic opens on the complement lookup that finds two values adding up to a target, compares two delivery manifests by counting their items rather than striking them off, and gives the one-pass template in Python, Java and TypeScript. It finds a missing seat number with the array as its own map, groups melodies by the steps between their notes, shows the pair an item makes with itself when it is recorded before it is looked up, and ends with an exercise on race times that differ by five seconds.
Contents
8 cardsnot started