Sub topic 1
What Hash Sets and Hash Maps Are For
Prerequisites
This chapter assumes you can write loops and functions in a mainstream language, and that you know how lists (arrays) are indexed. You should also know the basic idea of Big-O notation: O(n) means the work grows with the number of items, and O(1) means it stays about the same. The examples use Python.
The problem: finding things by value
Suppose you keep 100,000 email addresses in a list and want to know whether "[email protected]" is among them. A list has no shortcut. It checks each element in turn, so the work is O(n). Repeat that check for every incoming request and the cost adds up quickly.
Hash-based structures fix this. They find an item by computing where it should be stored, rather than by searching. There are two of them.
- A hash set stores unique values and answers one question: "is this value in the collection?"
- A hash map (also called a dictionary, associative array, or hash table) stores key-value pairs. You give it a key and get back the value linked to that key.
Both are built on the same internal design. A later chapter covers how it works. For now, treat them as tools with these promises: inserting, deleting and looking up an item take O(1) time on average, whatever the collection size.
Sets: membership and uniqueness
A set holds each value at most once. Building a set from a list drops the duplicates, and the in operator tests membership without scanning.
emails = ["[email protected]", "[email protected]", "[email protected]"]
unique = set(emails)
print(len(unique)) # 2
print("[email protected]" in unique) # TrueUse a set when you only care about whether a value is present, or when you need to remove repeats.
Maps: looking up a value by key
A map connects each key to a value. Keys are unique, so storing a second value under an existing key replaces the first.
ages = {"ana": 31, "bo": 27}
ages["cy"] = 45 # insert
ages["bo"] = 28 # replace
print(ages["ana"]) # 31
print("zed" in ages) # False
del ages["cy"] # deleteUse a map when you have an identifier and want the data that goes with it. Examples include a user ID that leads to a user record, a word that leads to its count, or a file path that leads to its cached contents.
Choosing between the three
The right choice depends on what question you ask most often.
| Task | Best fit | Why |
|---|---|---|
| Keep items in order and access them by position | List | Position is the natural index. |
| Ask "have I seen this value?" | Set | Average O(1) membership test. |
| Ask "what is known about this key?" | Map | Average O(1) lookup of the associated value. |
What you give up
Fast lookup by value has costs.
- Extra memory. A hash table keeps spare room so it can stay fast.
- Key rules. Keys must be hashable, and their equality and hash must agree. Python rejects a list as a key.
- No range queries. You cannot ask for "all keys between 10 and 20" without scanning everything.
- Limited order assumptions. Do not rely on a particular iteration order unless your language documents one.
The following chapters build on this one. They show the common patterns, then open up the table to explain why the average cost is O(1) and when it is not.
Exercise
A program receives a stream of order IDs and must report each ID the first time it appears and ignore later repeats. Which structure should it use, and why?
Show answer
A hash set. For each ID, test membership with in. If the ID is absent, report it and add it to the set. Each test is O(1) on average, whereas a list would be rescanned in full for every ID, making the total work grow with the square of the input size.
Exercise
You need to find the shipping address for a customer given a customer ID. Would you use a set or a map, and what are the key and the value?
Show answer
A map. The customer ID is the key and the address is the value. A set could only say whether an ID exists, not return data attached to it.