Hash Tables Explained: How Hashmaps Work Under the Hood

If you’ve ever used a dictionary in Python, an object in JavaScript, or an unordered_map in C++, you’ve already used a hash table. It’s one of the most important data structures in programming — and once you understand how it works internally, a lot of things in software development start to click.

In this post, we’ll cover everything from the basics of key-value pairs to hash functions, collision handling, and the trade-offs behind different implementations.


What Is a Hash Table?

A hash table (also called a hashmap) is a data structure that stores key-value pairs and allows you to look them up extremely fast — on average in O(1) time, regardless of how many items are stored.

The three core operations are:

OperationWhat it doesAverage Time
get(key)Returns the value associated with the keyO(1)
set(key, value)Stores the key-value pairO(1)
delete(key)Removes the key-value pairO(1)

One important note: if you set the same key twice with different values, the latest value always wins — the old one gets overwritten. Space complexity is O(n), where n is the number of stored pairs.


Key-Value Pairs

Every entry in a hash table has two parts:

  • Key — used to identify the entry (like a word in a dictionary)
  • Value — the data associated with that key (like the definition)

A phone book is a classic example: the key is a person’s name, and the value is their phone number. You look up the name (key) to get the number (value). Hash tables make this lookup nearly instant, no matter how large the phone book is.


How Is a Hash Table Implemented Internally?

Under the hood, a hash table needs a data structure to actually store the pairs. There are three options:

Array (Best Choice)

Arrays support random access by index in O(1) time. If we can convert any key into a valid array index, we get O(1) get and set for free. This is the standard implementation and what we’ll focus on.

Binary Search Tree (2nd Choice)

A BST organized by key gives O(log n) get/set/delete. This is slower than an array, but it has one advantage: keys are kept in sorted order. Use this when you need to iterate over keys in a sorted sequence.

Linked List (Avoid)

Get, set, and delete all cost O(n). There’s rarely a reason to implement a hashmap this way — the array-based approach already covers everything a linked list would offer, but faster.


The Hash Function

Here’s the core challenge: array indices are integers, but keys can be anything — strings, floats, objects. How do you convert "Alice" into a valid array index?

That’s the job of the hash function.

index = H(key)

A hash function takes any key and deterministically returns a number. For example:

H("Alice") = 5
→ store ("Alice", "1-201-123-4567") at array index 5

The Modulus Problem

In practice, standard library hash functions return very large numbers — far bigger than your array. To fit the result into the array, you apply a modulus:

index = H(k) mod m

Where k is the key and m is the size of the array. This guarantees the index always falls within bounds. For example, if H(k) = 1,482,910 and m = 10, then index = 0.

This works great — with one catch.


Hash Collisions

When two different keys hash to the same array index, that’s a collision.

H(k1) = 4,  H(k2) = 8,  array size m = 4
4 % 4 = 0
8 % 4 = 0  ← same index!

k1 and k2 are completely different keys, but they land in the same slot. We can’t just overwrite one with the other — we need to keep both. There are two standard ways to handle this.


Option 1: Chaining

In chaining, each array slot holds a linked list instead of a single value. When two keys collide at the same index, they’re both stored in the list at that slot.

Index 0: [ (key0, val0) ] → [ (key1, val1) ] → [ (key2, val2) ]
Index 1: [ empty ]
Index 2: [ (key3, val3) ] → [ (key4, val4) ]
Index 3: [ empty ]
Index 4: [ empty ]
Index 5: [ (key5, val5) ]

When you do a get, you go to the index and walk the linked list until you find the matching key.

The downside: In the absolute worst case, every single key hashes to the same index — turning the whole table into one long linked list with O(n) lookup. This is rare in practice, but it can happen with a bad hash function or a poorly sized array.


Option 2: Probing (Open Addressing)

Instead of linking collisions in a chain, probing keeps everything inside the array itself. When a collision occurs, you probe (scan) for the next available slot.

  • Linear probing: check index+1, index+2, index+3, …
  • Quadratic probing: check index+1², index+2², index+3², …

Probing avoids the overhead of linked list nodes and can be more cache-friendly, but it requires careful handling of deletions and can degrade if the array gets too full.


Preventing Collisions: Practical Improvements

Collisions can never be completely eliminated, but you can significantly reduce them with three strategies:

1. Use a prime number for array size. Since we use H(k) % m, the choice of m matters. Prime numbers distribute remainders more evenly and reduce the chance of clustering. For example, size 11 or 97 is better than size 10 or 100.

2. Resize when the table gets full. Most real-world implementations track the load factor — the ratio of stored entries to array size. When it exceeds a threshold (commonly 60–75%), the table is resized to a larger array and all entries are rehashed. This keeps collision rates low as the table grows.

3. Choose a good hash function. A good hash function spreads keys evenly across the array. Language standard libraries (Python’s hash(), Java’s hashCode(), C++’s std::hash) provide well-tested implementations — you almost never need to write one yourself.


The Good News

You don’t need to implement any of this from scratch. Every major programming language ships with a hash table in its standard library:

LanguageHash Table Type
Pythondict
JavaScriptObject / Map
JavaHashMap
C++unordered_map
Gomap

Understanding the internals helps you reason about performance — for instance, knowing that worst-case lookup is O(n) (not O(1)) helps you write better code under adversarial inputs or heavy load.


Summary

Hash tables are one of the most useful data structures you’ll encounter, and now you know why they work so well:

  • Key-value pairs let you store and retrieve data by meaningful identifiers
  • Array-based storage with a hash function gives average O(1) access
  • Modulus maps any hash value to a valid array index
  • Collisions are unavoidable, but handled via chaining or probing
  • Prime-sized arrays, load factor resizing, and good hash functions keep collision rates low in practice

Once you’re comfortable with hash tables, you’ll start seeing them everywhere — they’re the backbone of caches, databases, compilers, and countless interview problems.


Want to keep learning? Check out the rest of this series: → Graph Data Structures: A Beginner’s Guide → BFS & DFS: Graph Traversal Algorithms Explained → Dijkstra, MST & Union Find

Leave a Reply

Your email address will not be published. Required fields are marked *