Menu
Coddy logo textTech

Hash Map

Last updated

A hash map stores key-value pairs and lets you look up a value by its key in O(1) on average. It works exactly like a hash table, but each bucket entry carries both a key and its associated value. To store or fetch a pair, the key is hashed to a bucket index, then the bucket's chain is scanned for the matching key. Press play above to watch pairs get placed by hashed bucket and a value retrieved by its key.

This is the structure behind Python's dict, Java's HashMap, and JavaScript's Map/objects. Collisions are handled the same way as in a hash table - here, by separate chaining - so performance depends on a good hash function and a low load factor.

Time complexity

OperationAverageWorst case
Put (insert/update)O(1)O(n)
Get (lookup)O(1)O(n)
DeleteO(1)O(n)
SpaceO(n)O(n)

Hash map in common languages

LanguageType
Pythondict
JavaHashMap
JavaScriptMap / object
C++std::unordered_map
Gomap

Worked example

Inserting the pairs ("cat", 3), ("dog", 5), ("cat", 9), ("emu", 7) into a map with 8 buckets, using hash(key) % 8. Assume hash("cat") % 8 = 2, hash("dog") % 8 = 5, hash("emu") % 8 = 2:

StepStructureAction
Put ("cat", 3)bucket 2: [("cat", 3)]Hash to bucket 2; empty chain, so append the pair.
Put ("dog", 5)bucket 2: [("cat", 3)], bucket 5: [("dog", 5)]Hash to bucket 5; empty chain, so append the pair.
Put ("cat", 9)bucket 2: [("cat", 9)], bucket 5: [("dog", 5)]Hash to bucket 2; key "cat" already in chain, so update its value to 9.
Put ("emu", 7)bucket 2: [("cat", 9), ("emu", 7)], bucket 5: [("dog", 5)]Hash to bucket 2; collides with "cat", key not found, so append the pair.
Get "emu"bucket 2: [("cat", 9), ("emu", 7)]Hash to bucket 2; scan the chain, skip "cat", match "emu", return 7.

When to use a hash map

Use it whenAvoid it when
You need O(1) average lookup, insert, and delete by an exact key.You need keys kept in sorted order or range queries - use a balanced BST or sorted map.
Keys are hashable and equality is well defined (strings, ints, tuples).Keys are mutable and can change after insertion, which corrupts their bucket.
You are counting, deduplicating, caching, or indexing by an identifier.You need worst-case O(log n) guarantees rather than amortized average bounds.
Iteration order does not matter, or an insertion-ordered map suffices.Memory is very tight - buckets, load-factor headroom, and pointers add overhead.

Hash Map code

A clean, runnable Hash Map implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Hash Map code in Python

Python
1# Python's built-in dict is a hash map: O(1) average2# insert, lookup, and delete.3inventory = {"apple": 3, "banana": 7}4
5# Insert and update6inventory["cherry"] = 57inventory["apple"] += 28
9# Lookup, with .get for a safe default on missing keys10print("apple: ", inventory["apple"])11print("mango: ", inventory.get("mango", 0))12
13# Membership test and delete14print("banana in stock:", "banana" in inventory)15del inventory["banana"]16print("banana in stock:", "banana" in inventory)17
18# Iterate over key-value pairs19for fruit, count in sorted(inventory.items()):20    print(f"{fruit}: {count}")21
22# Classic hash map use case: counting frequencies23words = "the quick brown fox jumps over the lazy dog the end".split()24freq = {}25for word in words:26    freq[word] = freq.get(word, 0) + 127
28print("Occurrences of the:", freq["the"])29print("Most common word:  ", max(freq, key=freq.get))
Run this code in the Python Playground

Hash Map FAQ

What is the difference between a hash map and a hash table?
They're essentially the same structure - an array of buckets addressed by a hash of the key. In common usage "hash table" often refers to a set of keys or the general technique, while "hash map" emphasizes storing key-value pairs. Some languages also draw a thread-safety distinction (e.g. Java's Hashtable vs HashMap), but the core algorithm is identical.
What is the time complexity of a hash map?
Put, get, and delete are O(1) on average with a good hash function and a low load factor. In the pathological case where all keys collide into one bucket, they degrade to O(n), which is why resizing and good hashing matter.
How does a hash map handle two keys that hash to the same bucket?
It resolves the collision. This visualization uses separate chaining: each bucket holds a small list, and a new pair whose key hashes there is appended to that list. On lookup, the map scans the short chain for the matching key. The alternative technique is open addressing, which probes for another slot in the array.
Hash map vs binary search tree: which should I use?
Use a hash map when you only need lookup by exact key and want O(1) average operations. Use a balanced binary search tree (like a TreeMap or std::map) when you need keys in sorted order, range queries, or predecessor/successor lookups, which cost O(log n). The BST trades a bit of speed for ordering guarantees a hash map cannot provide.
What is the load factor and why does it trigger resizing?
The load factor is the ratio of stored entries to buckets. As it rises, chains grow longer and average lookups slow down, so most implementations resize (typically double the buckets and rehash everything) once it passes a threshold like 0.75. Resizing is O(n) but rare, so it is amortized away and keeps average operations O(1).
Can I use a mutable object like a list as a hash map key?
Usually no. Keys must be hashable and their hash must stay constant while they are in the map - Python raises TypeError: unhashable type for a list, for example. If you mutate a key after inserting it, its hash changes and the map can no longer find it in the right bucket, silently losing the entry. Use immutable keys such as strings, numbers, or tuples.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED