TExcelTAD

Hash Maps

A hash map (also called a dictionary or associative array) stores key → value pairs. It is a hash table where every bucket entry holds a key and its value. The key decides the bucket; the value just travels along. Looking up the value for a key is O(1) on average.

Examples: a phone book (name → number), a word counter (word → count), a cache (URL → page), a configuration (setting → value).

Buckets of key-value pairs

The animation shows where the keys go; in a hash map each stored key also carries its value. With 7 buckets, the product codes below hash like this:

Max and Ian collide in bucket 0, and Kim and Sam collide in bucket 2. Putting Kim again doesn't add a second entry: in a hash map it updates the existing key's value.

Implementation

python · try it yourself
class HashMap:
    def __init__(self, size=7):
        self.buckets = [[] for _ in range(size)]

    def _bucket(self, key):
        return self.buckets[sum(ord(c) for c in key) % len(self.buckets)]

    def put(self, key, value):
        bucket = self._bucket(key)
        for i, (k, _) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)       # existing key: update
                return
        bucket.append((key, value))            # new key: add a pair

    def get(self, key, default=None):
        for k, v in self._bucket(key):
            if k == key:
                return v
        return default

    def remove(self, key):
        bucket = self._bucket(key)
        for i, (k, _) in enumerate(bucket):
            if k == key:
                del bucket[i]
                return True
        return False

stock = HashMap()
stock.put("Max", 12)
stock.put("Ian", 4)
stock.put("Kim", 30)
stock.put("Sam", 7)
print("Sam:", stock.get("Sam"))
stock.put("Kim", 25)                 # update, not a new entry
stock.remove("Max")
print("Max:", stock.get("Max", "not found"))
for i, bucket in enumerate(stock.buckets):
    if bucket:
        print(i, bucket)
Sam: 7
Max: not found
0 [('Ian', 4)]
2 [('Kim', 25), ('Sam', 7)]

Python's dict

Python's dict is a hash map that also remembers insertion order (since Python 3.7). The essentials:

python · try it yourself
ages = {"Ana": 31, "Ben": 27}
ages["Cleo"] = 35               # insert
ages["Ben"] = 28                # update
print(ages["Ana"])              # lookup; raises KeyError if missing
print(ages.get("Dev", "unknown"))
print("Cleo" in ages)           # membership tests the keys
del ages["Ana"]
for name, age in ages.items():
    print(name, age)
31
unknown
True
Ben 28
Cleo 35

Pattern: counting

Counting occurrences is the classic hash map job. dict.get(key, 0) + 1 works, and collections.Counter does it for you:

python · try it yourself
from collections import Counter

text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)

c = Counter(text.split())
print(c.most_common(2))
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
[('the', 3), ('and', 2)]

Pattern: grouping

Map each key to a list of items. collections.defaultdict(list) creates the empty list the first time a key is used:

python · try it yourself
from collections import defaultdict

words = ["listen", "google", "silent", "enlist", "elgoog", "stone", "notes"]
groups = defaultdict(list)
for w in words:
    groups["".join(sorted(w))].append(w)    # anagrams share their sorted letters
for key, group in groups.items():
    print(key, group)
eilnst ['listen', 'silent', 'enlist']
eggloo ['google', 'elgoog']
enost ['stone', 'notes']

Pattern: "have I seen the complement?"

Find two numbers in a list that add up to a target. The naive way checks every pair, O(n²). With a hash map from value to index, one pass is enough: for each number, ask whether target - number has already been seen.

python · try it yourself
def two_sum(nums, target):
    index_of = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in index_of:
            return index_of[need], i
        index_of[n] = i
    return None

prices = [14, 3, 22, 9, 17, 5]
print(two_sum(prices, 26))     # 9 + 17
print(two_sum(prices, 100))
(3, 4)
None

Tip: Whenever a solution has a nested loop that searches for "a matching item", ask whether a hash map could remember the items instead. It often turns O(n²) into O(n).

Rules for keys

Rule Why
Keys must be hashable (immutable): str, int, tuple a key's hash must never change
Keys are unique putting an existing key overwrites its value
Values can be anything they are not hashed
Lookups compare keys with == after matching the hash two keys that are equal must have equal hashes

Test yourself

What happens when you put a key that already exists in a hash map?

  1. A second entry is added
  2. Its value is replaced
  3. An error is raised
  4. The key is removed

What does counts.get(word, 0) return when word is not a key?

  1. None
  2. KeyError
  3. 0
  4. An empty list

Using a hash map, what is the time complexity of the one-pass two-sum algorithm?

  1. O(1)
  2. O(n)
  3. O(n log n)
  4. O(n²)