Curious Minds

Clear answers to science and history questions

How Hash Tables Work: Beginner-Friendly Guide

· 7 min read · Science

A hash table is a data structure that stores key-value pairs and uses a hash function to map each key to an index in an array, so that looking up, inserting, or deleting a value takes roughly constant time on average. In other words, instead of searching through every item, the hash function tells you almost exactly where to look.

What Is a Hash Table, Really?

Imagine a row of numbered mailboxes. To store a letter for "Alice," you don't scan every box; you compute a number from her name and drop the letter into that box. Later, to retrieve Alice's letter, you compute the same number and open that box. That's the core idea of a hash table: a hash function turns a key (like a name or ID) into an integer, and that integer becomes an array index. The array itself is often called the bucket array or slot array.

Hash tables go by many names: hash map, dictionary, associative array, symbol table. They appear everywhere—Python's dict, Java's HashMap, JavaScript's Map and plain objects, and the internals of database indexes and caches. The concept dates back to the 1950s and became fundamental in compiler design and file systems.

The Hash Function: Turning Keys into Indexes

A hash function takes a key of any type—string, number, object—and returns a fixed-size integer. A good hash function has three properties:

  • Deterministic: the same key always produces the same hash value.
  • Fast to compute: hashing should be cheap relative to searching.
  • Uniform distribution: keys should spread evenly across the available indexes to minimize collisions.

For example, a simple (but poor) hash for strings might add up character codes. A better one mixes bits so that similar strings produce very different hashes. Cryptographic hashes like SHA-256 are also hash functions, but they are deliberately slow and are not used inside hash tables—tables need speed, not security.

Once you have a hash integer, you reduce it to a valid array index, typically with the modulo operator: index = hash % array_size. If the array has 16 slots, a hash of 42 lands in slot 10 (42 % 16 = 10).

How Insertion, Lookup, and Deletion Work

The operations follow a simple pattern:

  1. Insert: compute the hash of the key, reduce it to an index, and store the key-value pair at that index. If the slot is occupied by a different key, resolve the collision (see below).
  2. Lookup: compute the same hash and index, then check whether the stored key matches. If it does, return the value. If not, follow the collision-resolution strategy to find the right entry.
  3. Delete: find the entry the same way as lookup, then remove it or mark it as deleted (depending on the collision strategy).

Because the hash function jumps directly to a slot, these operations take O(1) time on average—constant time regardless of how many items are stored. That's the headline benefit. In the worst case, when many keys collide, operations degrade to O(n), where n is the number of entries.

Collisions: When Two Keys Want the Same Slot

No hash function can avoid collisions entirely unless the array is larger than the set of all possible keys. Since the array is finite, different keys will sometimes map to the same index. Hash tables handle this in two main ways:

  • Separate chaining: each array slot holds a linked list (or another structure) of entries. Colliding keys are appended to the list. Lookup walks the list until it finds the matching key. Chaining is simple and tolerates high load factors, but linked lists add memory overhead and can hurt cache performance.
  • Open addressing: all entries live directly in the array. When a slot is taken, the table probes other slots—linearly (check the next slot), quadratically (check slots at increasing offsets), or with double hashing (use a second hash to pick the step size). Lookup follows the same probe sequence. Open addressing is more cache-friendly but requires careful deletion (often using tombstones) and performs poorly when the table is too full.

A common misconception is that collisions mean the hash table is broken. In reality, collisions are normal and expected; the table's design is all about handling them gracefully.

Load Factor and Resizing

The load factor is the ratio of stored entries to array slots. A load factor of 0.75, for example, means the table is 75% full. As the load factor rises, collisions become more frequent and performance degrades. Most implementations resize (rehash) the table when the load factor crosses a threshold—often around 0.7 to 0.75 for open addressing, and 1.0 or higher for chaining.

Resizing means allocating a larger array (typically double the size) and reinserting every existing entry, because the index formula depends on the array size. This is an O(n) operation, but it happens infrequently enough that the amortized cost per insertion remains O(1). Choosing a good initial capacity and growth factor is a practical tuning knob.

Choosing a Hash Function and Table Size

For beginners, the main factors are:

  • Key type: integers hash easily; strings need a mixing function; composite keys need to combine their parts' hashes.
  • Distribution: avoid hash functions that cluster similar keys. For example, hashing only the first character of a name would put all "A" names in one slot.
  • Table size: prime numbers are often used with modulo hashing to reduce patterns; power-of-two sizes allow fast bit-masking (hash & (size - 1)) but require a high-quality hash to avoid clustering.
  • Language defaults: most standard libraries provide well-tested hash functions and resizing policies. Use them unless you have a specific reason not to.

Common Problems and How to Spot Them

Hash tables are not magic. Watch for these issues:

  • Poor hash quality: many collisions cause long chains or probe sequences, slowing operations. Test with realistic data.
  • Mutable keys: if a key's hash changes after insertion (e.g., a list used as a key), the table can no longer find it. Use immutable keys.
  • Denial-of-service attacks: if an attacker can craft keys that all collide, they can force worst-case O(n) behavior. Some languages add randomization to hash functions to mitigate this.
  • Memory overhead: chaining and resizing consume extra memory. For small collections, a simple array or list may be faster and lighter.

Hash Tables vs. Other Data Structures

Hash tables excel at exact-key lookup, insertion, and deletion. They do not maintain order, so they are a poor choice when you need sorted data or range queries—balanced trees (like red-black trees) or sorted arrays serve those needs better. Hash tables also do not support efficient "find the closest key" operations. For small datasets, the constant factors of hashing may outweigh the asymptotic advantage, and a linear scan can be faster. In short: use a hash table when you need fast, unordered key-value access.

Frequently Asked Questions

What is the difference between a hash table and a hash map?

In practice, the terms are often used interchangeably. Strictly, a hash table is the underlying data structure, while a hash map is a common name for an associative array implemented with a hash table. Some languages distinguish them by thread-safety or interface, but the core mechanism is the same.

Can hash tables store duplicate keys?

No—by definition, each key maps to one value. Inserting a duplicate key typically overwrites the existing value. If you need multiple values per key, store a list or another collection as the value.

Why is lookup O(1) on average but O(n) in the worst case?

On average, a good hash function spreads keys evenly, so each slot holds few entries. In the worst case, all keys collide into the same slot, turning lookup into a linear scan through n entries. This is rare with a good hash but possible, especially with adversarial input.

Are hash tables always faster than arrays?

Not always. Arrays offer O(1) access by index but require you to know the index. Hash tables add hashing overhead and memory cost. For small collections or when keys are dense integers, an array may be simpler and faster.

What happens when a hash table runs out of space?

It resizes—allocates a larger array and rehashes all entries. This is automatic in most implementations, but it costs time and memory. You can often pre-size a table if you know roughly how many entries you'll store.

Can I use a hash table for ordered data?

No, standard hash tables do not preserve insertion order or sort keys. Some implementations (like Python's dict) preserve insertion order as a side effect, but they still don't support efficient ordered operations like range queries. Use a tree or sorted structure for that.

In this article
  1. What Is a Hash Table, Really?
  2. The Hash Function: Turning Keys into Indexes
  3. How Insertion, Lookup, and Deletion Work
  4. Collisions: When Two Keys Want the Same Slot
  5. Load Factor and Resizing
  6. Choosing a Hash Function and Table Size
  7. Common Problems and How to Spot Them
  8. Hash Tables vs. Other Data Structures
  9. Frequently Asked Questions