Hash table
Хеш-таблица
This data structure stores key–value pairs and uses a hash of the key to work out where to look. For example, it can find a user profile by username without scanning every profile.
Also known as: hash map, хеш-мапа, словарь
What a hash table does
Say you have a collection of products and need to retrieve one by its SKU. An unsorted list makes you check products one at a time. A hash table uses the SKU to narrow down where to look. Each key has at most one associated value, so inserting a value for an existing key updates the entry.
A map or dictionary is a collection that associates keys with values. A hash table is one way to implement it, often called a hash map when it stores key–value pairs. A map can also be backed by a tree, which is useful when you need to visit keys in sorted order.
What happens during a lookup?
A hash function turns the key into an integer. The table converts that integer into a starting position in an internal array, for example by taking the remainder after dividing by the array's capacity. Two distinct keys can land at the same position even if their full hash values differ. That's a collision. To establish a match, the table still needs to check key equality.
Two common ways to handle collisions are:
- Separate chaining: Each array position has a bucket that can hold multiple entries. A lookup searches only the bucket selected for that key.
- Open addressing: Entries live in the array itself. When a slot holds a different key, the table follows a probe sequence to check other slots. Simply clearing a slot on deletion can break lookups that need to probe past it, so some implementations leave a marker called a tombstone.
The load factor is the number of entries divided by the number of array positions. As it rises, collisions generally become more costly, so tables typically grow and redistribute entries. With well-distributed hashes, a controlled load factor, and constant-time hashing and equality checks, lookup and deletion take expected O(1) time, and insertion takes expected amortized O(1). One insertion can still cost O(n) if it triggers a resize. In basic implementations, a lookup can also degrade to O(n) when collisions force it to inspect nearly every entry.
Example: count items by key
counts = {}
for sku in ['A12', 'B07', 'A12']:
counts[sku] = counts.get(sku, 0) + 1
print(counts['A12']) # 2
Python's dict stores one counter per SKU. The first occurrence starts the counter at 1; later occurrences update the existing entry. The same lookup pattern is useful for indexing records by ID or caching results by input.
Common mistakes and interview use
Equal keys must have equal hashes, but equal hashes don't prove that two keys are equal. If you change a stored key in a way that affects hashing or equality, lookup may stop working as intended. Also, iteration order depends on the implementation: Python's dict preserves insertion order, but hash tables as a group don't promise that order or sorted keys.
In interviews, Two Sum is a classic example. As you scan the array, keep a map from previously seen numbers to their indices. Look up the complement before storing the current number so you don't use the same index twice. This trades O(n) extra space for expected O(n) time.