AlgoMaster Logo

Introduction to Hash Tables

High Priority19 min readUpdated November 9, 2026
Listen to this chapter
Unlock Audio

Premium Video

This video is available to premium subscribers only

Unlock Full Access

Hash tables are one of the most useful and widely used data structures in computer science.

They let us store and look up data very quickly, which is why they're used in so many real-world applications.

Hash tables are used almost everywhere in real-world software:

  • Databases use them to build hash indexes for fast lookups.
  • Compilers use them to manage symbol tables.
  • Caching systems use them to find a stored result by its key.
  • Built-in data structures like Python's dict and Java's HashMap are hash tables.

If you're preparing for coding interviews, understanding hash tables is essential. You'll encounter them in many different problems, where they can often help you turn a slow solution into a much more efficient one.

This chapter covers:

  • What a hash table is and how hashing maps keys to array positions
  • How hash tables handle collisions with separate chaining and open addressing
  • Load factor, resizing, and rehashing
  • The time and space complexity of the core operations
  • When to use a hash table in coding interviews

What Is a Hash Table?

A hash table is a data structure that stores data as key-value pairs and lets us look up a value using its key in constant time on average.

a
:
1
b
:
2
c
:
3

But how does it make these lookups so fast?

At its core, a hash table uses an array.

It also uses a hash function, which takes a key and determines where it should be stored in the array.

Each position in this array is typically called a bucket.

So, a hash table has three main components:

  1. An array of buckets.
  2. A hash function that maps keys to buckets.
  3. A way to handle collisions when multiple keys map to the same bucket.

Let's look at each one.

The Hash Function

The hash function is what makes a hash table work.

Its job is to take a key, which could be a string, an integer, or an object, and convert it into a numerical hash value.

We then use this hash value to calculate an index in the underlying array, often using the modulo operation:

Let's look at an example.

Suppose our hash table has 16 buckets. We want to store the key "apple", and our hash function produces the value 1,829,374.

When we take this number modulo 16, we get 14:

So, we store "apple" in bucket 14.

Later, when we want to retrieve "apple", we pass the same key through the hash function. We get the same bucket index, 14, and can go directly to that position instead of searching through the entire array.

That's the basic idea behind fast lookups in a hash table.

What Makes a Good Hash Function

Not all hash functions are equally good. A good hash function should have three important properties.

1. Consistency

The same key must always produce the same hash value while it's stored in the table.

Otherwise, we might insert a key into one bucket and later look for it in a completely different one.

2. Uniform distribution

Ideally, the hash function distributes keys as evenly as possible across the available buckets.

If too many keys end up in the same bucket, we'll have more collisions, and the hash table becomes less efficient.

3. Speed

We calculate a hash whenever we insert, look up, or delete a key, so the hash function itself needs to be fast.

For fixed-size integers, computing a hash can take constant time. But for a string of length L, it may take O(L) time because we might need to process every character.

Collisions

Even with a good hash function, two different keys can end up in the same bucket. This is called a collision.

And collisions are unavoidable.

For example, imagine a hash table with 16 buckets. If we insert 17 different keys, at least two of them must end up in the same bucket. There simply aren't enough buckets to give every key its own position. This is known as the pigeonhole principle.

And even with millions of buckets, collisions are still possible, because there are far more possible keys than available positions.

So, rather than trying to eliminate collisions entirely, hash tables need a way to handle them. There are two common approaches:

  • Separate chaining
  • Open addressing

Let's look at how each one works.

Separate Chaining

The idea is simple.

Instead of storing just one entry in each bucket, we allow each bucket to hold multiple entries, usually in a linked list. When two keys map to the same bucket, we store both of them in that bucket's list.

When inserting a key, we first check whether it already exists in the list:

  • If it does, we update its value.
  • Otherwise, we add a new key-value pair.

Lookups work in a similar way. We calculate the bucket index, go directly to that bucket, and search through its entries until we find the matching key.

Example: Four Buckets

Suppose our hash table has four buckets.

  1. First, we insert apple with value 1. Let's say apple maps to bucket 2. Since the bucket is empty, we simply store it there.
  2. Next, we insert grape with value 2. Suppose grape also maps to bucket 2. Now we have a collision.
  3. Instead of replacing apple, we add grape to the same linked list. So, bucket 2 now contains both entries.

Later, when we want to retrieve grape, we calculate its hash and go directly to bucket 2. We then search through the linked list, find grape, and return its value.

That's how separate chaining handles collisions.

Implementing Separate Chaining

We start by creating an array of buckets, where each bucket holds a linked list. Each entry in the list stores a key and its corresponding value.

  • put: we calculate the bucket index using the key's hash and search through that bucket's list. If the key already exists, we update its value. Otherwise, we add a new entry.
  • get: we calculate the bucket index, search through the linked list, and return the value if we find the key. If the key doesn't exist, we need to handle that case explicitly. In the implementation below, get returns null (or the language's equivalent).
  • remove: we find the matching key and remove its entry from the linked list.

This version also tracks the load factor and doubles the number of buckets when the table gets too full. We'll cover load factor and resizing later in this chapter.

Trade-offs of Separate Chaining

Separate chaining has a few advantages. It's relatively easy to implement, and we can store more entries than the number of buckets, since each bucket can hold multiple entries.

But there's a downside. If too many keys end up in the same bucket, searching through that bucket becomes slower:

  • If a bucket contains k entries, searching its linked list takes O(k) time.
  • In the worst case, if every key maps to the same bucket, a lookup could take O(n) time.

At that point, we're basically searching through a regular linked list, which defeats the purpose of using a hash table.

Another drawback is the extra memory usage. Each linked-list entry needs additional space to store references to other nodes.

So, to keep separate chaining efficient, we need a good hash function and enough buckets to keep the chains short.

Open Addressing

Unlike separate chaining, where each bucket can hold multiple entries, open addressing stores at most one entry in each array slot.

So, what happens when two keys map to the same slot?

Instead of creating a linked list, we look for another available slot in the array. This process is called probing.

The simplest approach is linear probing:

  • When a slot is already occupied by another key, we check the next slot.
  • If that's also occupied, we keep moving forward, one slot at a time, until we find an empty one.
  • If we reach the end of the array, we wrap around to the beginning.

Example: Eight Slots

Suppose our hash table has eight slots.

  1. First, we insert apple, which maps to slot 3. Since it's empty, we store apple there.
  2. Next, we insert grape, which also maps to slot 3. That slot is already occupied, so we check slot 4. It's empty, so we store grape there.
  3. Now, let's insert mango. Suppose mango maps to slot 4. Slot 4 already contains grape, so we move to slot 5 and store mango there.
Scroll

Slot

Stored key

Home slot

How it got there

0

(empty)

 

 

1

(empty)

 

 

2

(empty)

 

 

3

apple

3

stored at its home slot

4

grape

3

slot 3 was taken; probed to 4

5

mango

4

slot 4 was taken; probed to 5

6

(empty)

 

 

7

(empty)

 

 

Notice that all three keys are stored directly in the array, without any linked lists.

That's how linear probing works.

Deletion and Tombstones

Deletion is a little more complicated with open addressing.

Let's go back to our example. grape is stored at slot 4, and mango is stored at slot 5.

Suppose we delete grape. If we simply mark slot 4 as empty, we run into a problem.

Later, when we search for mango, we start at slot 4, because that's where mango originally hashed. We see an empty slot and might incorrectly assume that mango doesn't exist. But mango is actually in the very next slot, slot 5.

To solve this, we use a special marker called a tombstone. Instead of marking the slot as empty, we mark it as deleted. This tells the lookup operation to keep searching, because there might be more entries farther along the probing sequence.

We can also reuse deleted slots when inserting new keys. But first, we need to make sure the key doesn't already exist farther along the sequence.

So, each slot can now have three possible states: empty, occupied, or deleted.

Implementing Linear Probing

Each slot needs to hold a key, its value, and the slot's state. The implementation below stores an entry object in each slot. An empty slot is null, and a deleted slot keeps its entry with a deleted flag set. You could also use three parallel arrays: one for keys, one for values, and one for each slot's state.

  • put: we calculate the starting index using the hash function. If the slot is occupied, we compare the keys. If they match, we update the value. Otherwise, we move to the next slot, using modulo to wrap around at the end of the array. We continue until we find an available slot where we can store the new key-value pair. The first tombstone we pass is remembered and reused.
  • get: lookups follow the same probing sequence. We start at the key's original hash index and keep checking slots until we find a matching key or reach an empty slot, which means the key doesn't exist.
  • remove: we find the matching key and mark its slot as deleted.

There's one important thing to remember. We should never check more slots than the table contains. Otherwise, if the table is full and we're searching for a missing key, we could get stuck in an infinite loop. Similarly, if an insertion can't find an available slot, we need to either resize the table or report that it's full.

This implementation handles that by never letting the table fill up. Tombstones count toward the load factor (so remove does not decrease size), and the table doubles as soon as more than half of its slots are in use. Resizing also clears out the tombstones. Because at least half of the slots are always empty, every probe sequence reaches an empty slot.

This is a teaching implementation. Production hash tables add many refinements, such as stronger hash mixing to spread out poor hashCode() results, tree-based buckets for long chains, and protection for concurrent access.

Clustering and Other Probing Strategies

Linear probing is simple and can be very fast in practice. One reason is that it accesses nearby memory locations, which makes it cache-friendly.

But it also has an important drawback called primary clustering.

As we insert more keys, groups of consecutive occupied slots start forming. And once a cluster forms, it tends to grow even larger. Any new key that hashes into that region may have to search through several occupied slots before finding an empty one. As these clusters grow, inserts and lookups become slower.

To reduce this problem, we can use other probing strategies.

Quadratic probing. Instead of checking the next slot every time, we use increasing offsets, such as 1, 4, 9, and 16.

Quadratic probing breaks up primary clusters, but two keys with the same home slot still follow the exact same probe sequence. This is called secondary clustering. To guarantee that quadratic probing finds an empty slot, the table size is usually a prime number and the load factor is kept below 0.5.

Double hashing. Here, we use a second hash function to determine how far to move with each probe.

Because the step size depends on the key, two keys with the same home slot usually take different paths. For this to work, hash2(key) must never be zero, and it must share no common factor with the table size, so the sequence can reach every slot.

Both approaches can help reduce clustering, but they require carefully chosen table sizes and probing rules to work correctly.

Scroll

Strategy

Clustering

Cache friendliness

Linear probing

Primary clustering

Excellent (sequential slots)

Quadratic probing

Secondary clustering

Good

Double hashing

Little clustering

Moderate (scattered slots)

Open addressing also uses less memory than separate chaining in many cases, because we don't need a separate linked-list node for every entry.

But there's an important limitation. We can't store more entries than the number of available slots. And as the table fills up, finding an empty slot becomes increasingly expensive.

This brings us to another important concept: the load factor.

Load Factor

The load factor tells us how full a hash table is. We calculate it by dividing the number of stored entries by the number of buckets or slots:

For example, suppose our hash table has 16 buckets and stores 12 entries. The load factor is 12 / 16 = 0.75.

The load factor means slightly different things for our two collision-handling strategies:

  • With separate chaining, it represents the average number of entries per bucket. Since each bucket can hold multiple entries, the load factor can be greater than 1.
  • With open addressing, it represents the fraction of occupied slots, so it can never exceed 1.

As the load factor increases, handling collisions generally becomes more expensive, and operations can start slowing down.

But there's a trade-off. If we keep the load factor too low, we end up wasting a lot of memory on unused space.

So, hash tables typically use a load-factor threshold to decide when to resize. The right threshold depends on the implementation and how collisions are handled:

Scroll

Implementation

Collision handling

Resizes when the load factor exceeds

Java HashMap

Separate chaining

0.75

Python dict

Open addressing

about 2/3

C++ std::unordered_map

Separate chaining

1.0 (configurable with max_load_factor)

Open-addressing tables usually resize earlier, because probe sequences get long quickly as the table fills.

Resizing and Rehashing

So, what happens when a hash table reaches its load-factor threshold?

Typically, we increase its capacity, often by doubling the size of the underlying array.

But there's a catch. We can't simply copy every entry into the same position in the new array.

Why? Because the bucket index depends on the table's capacity. When the capacity changes, the same key might map to a completely different bucket. For example, a key with hash value 13 is in bucket 13 % 8 = 5 in an 8-bucket table, but in bucket 13 % 16 = 13 after the table grows to 16 buckets.

So, we need to go through all existing entries, calculate their new positions, and insert them into the larger table. This process is called rehashing:

  1. Allocate a new array, typically twice the current size.
  2. Go through every entry in the old table.
  3. Calculate each entry's bucket index using the new capacity.
  4. Insert it into the new table.

Rehashing takes O(n) expected time, assuming hashing and insertion remain efficient.

That might sound expensive, but here's the important thing: we don't rehash after every insertion.

Since the table grows geometrically, resizing happens relatively infrequently. And the cost gets spread across many inexpensive insertions. This is similar to how dynamic arrays grow.

So, even with resizing, insertion still takes O(1) expected amortized time, assuming a good hash function.

Java's HashMap adds one more safeguard. When a single bucket's chain reaches 8 entries and the table has at least 64 buckets, that bucket is converted from a linked list into a balanced tree. This keeps a crowded bucket's lookup at O(log k) instead of O(k).

Time and Space Complexity

There are three main operations: insertion, lookup, and deletion.

All three follow the same basic process. We calculate the key's hash, find its bucket, and use our collision-handling strategy to locate the correct entry.

Scroll

Operation

Average

Worst case

Insert

O(1) expected amortized

O(n)

Lookup

O(1)

O(n)

Delete

O(1)

O(n)

Space

O(n + capacity)

O(n + capacity)

With a good hash function and a reasonable load factor, lookup and deletion take O(1) time on average. Insertion also takes O(1) expected amortized time, even when we account for occasional resizing.

But in the worst case, operations can take O(n) time. For example, with separate chaining, all keys could end up in the same bucket. And with open addressing, we might need to search through a large portion of the table.

One important thing to remember is that these bounds assume hashing and comparing keys take constant time. For longer keys, like strings, these operations can take additional time.

In terms of space, a hash table uses O(n) plus its allocated capacity. When the capacity is proportional to the number of entries, the overall space complexity is O(n).

Hash Tables in Practice

In practice, you rarely need to implement a hash table from scratch. Most programming languages already provide highly optimized implementations.

For example, in Java, we typically use HashMap. In Python, we use dict. And in C++, we use unordered_map.

All of them support the same basic operations. We can insert key-value pairs, look up values using their keys, check whether a key exists, and remove entries.

But there are some important differences between them. For example, they may handle missing keys, resolve collisions, resize their tables, and maintain iteration order differently:

  • Missing keys: Java's map.get(key) returns null, Python's d[key] raises a KeyError (use d.get(key) to get None instead), and C++'s map[key] inserts a default value if the key is missing.
  • Iteration order: Python's dict keeps insertion order, Java's HashMap and C++'s unordered_map make no ordering promise, and Go deliberately randomizes map iteration order.

So, while the underlying concept is the same, it's important to understand how hash tables work in the programming language you're using.

Java has two main hash-based collections: HashMap<K, V> for key-value pairs and HashSet<E> for distinct elements. LinkedHashMap preserves insertion order; Hashtable is the legacy synchronized version and generally not used in new code.

For interview problems, the built-in is almost always the right choice. A hand-written hash table usually comes up only when a problem asks you to show how hashing or collision handling works.

Hash Maps, Hash Sets, and Tree Maps

There's another related data structure worth knowing about: the hash set.

A hash map stores key-value pairs. But sometimes, we don't need to store a value. We just want to know whether an element exists. That's where a hash set comes in.

For example, suppose we want to count how many times each number appears in an array. A hash map would be a good choice, because we can store each number as a key and its frequency as the value.

But what if we only want to track which numbers we've already seen? In that case, a hash set is a simpler choice.

Both support fast membership checks on average.

Now, what if we need our keys in sorted order? Or we want to efficiently find keys within a particular range? A hash table can't do either well, because keys are spread across buckets in no particular order.

In those cases, a tree-based map might be a better choice. For example, Java provides TreeMap, and C++ provides map. These typically support operations in O(log n) time while keeping keys sorted.

Scroll

Operation

Unsorted array

Sorted array

Balanced BST (tree map)

Hash table (average)

Insert

O(1) at the end

O(n)

O(log n)

O(1)

Search by key

O(n)

O(log n)

O(log n)

O(1)

Delete by key

O(n)

O(n)

O(log n)

O(1)

Find min / max

O(n)

O(1)

O(log n)

O(n)

Find the next larger key

O(n)

O(log n)

O(log n)

O(n)

Iterate in sorted order

O(n log n)

O(n)

O(n)

O(n log n)

Space

O(n)

O(n)

O(n)

O(n)

Hash tables are the best choice for lookups, inserts, and deletes by key. When the work depends on order, such as minimum, maximum, the next larger key, range queries, or sorted iteration, use a tree map instead.

When to Use a Hash Table

So, when should you use a hash table in coding interviews? There are a few common patterns.

1. Fast lookup

Whenever a problem asks something like "Have I seen this value before?" or "What's the value associated with this key?", a hash table is often a great choice.

For example, counting word frequencies or mapping user IDs to user objects.

2. Removing duplicates

Suppose you're given an array and want to find all the unique elements. Instead of comparing every element with every other element, you can simply add them to a hash set.

3. Grouping elements

Whenever you need to group items based on a shared property, a hash table can make things much simpler. The key represents the group, and the value stores the items belonging to it.

A classic example is the Group Anagrams problem, where we group strings that have the same character-count signature. For example, eat, tea, and ate all have the signature a1e1t1, so they end up in the same group.

4. Caching

If we've already computed a result for a particular input, we can store it in a hash table. The next time we encounter the same input, we can simply retrieve the result instead of computing it again.

5. Optimizing brute-force solutions

Finally, one of the most useful patterns is optimizing brute-force solutions.

Suppose your current solution takes O(n²) time because you're using nested loops to compare every pair of elements. Before settling for that solution, ask yourself: can I store information about the elements I've already processed and look it up directly instead of searching through them again?

If the answer is yes, a hash table might be exactly what you need.

Two Sum is the classic example. Given [3, 8, 5, 1, 9, 6] and a target of 15, the nested-loop approach checks up to 15 pairs. With a hash map of the values seen so far, we make one pass: for each value v, we check whether 15 - v is already in the map. When we reach 6, we find 9 at index 4 and return [4, 5], in O(n) time.

Wrap-Up

That's how hash tables work.

We've seen how hashing maps keys to array positions, how separate chaining and open addressing handle collisions, and how resizing helps keep operations efficient. We've also covered when to use hash tables and how to recognize problems where they can make our solutions faster.

To strengthen your understanding, try implementing a simple hash table yourself using both separate chaining and open addressing. Working through collisions, probing, deletion, and resizing on your own will give you a much better understanding of how everything works behind the scenes.

Quiz

Introduction to Hash Tables Quiz

10 quizzes