Find a course

Module 2: Arrays, Lists, Stacks, Queues and Hash TablesLesson 6 of 1313 min

Hash Tables

See how hash functions turn keys into array positions, handle collisions and load factor, and use maps and sets to turn O(n²) problems into O(n).

Step 1 of 11Learn

From O(n²) to O(n) with one structure

Here's a classic problem: given an array of numbers and a target, find two numbers that add up to the target. The brute-force approach checks every pair: O(n²). For 100,000 numbers, that's about 5 billion pairs.

A better approach walks through the array once. For each number x, it asks: have I already seen target − x? If you can answer that question in constant time, the whole algorithm is O(n). The structure that makes this possible is the hash table.

A hash table stores key-value pairs in an array of buckets. To store or find a key, it runs the key through a hash function that turns it into a large integer, then reduces that to a bucket index, often with the modulo operator: index = hash(key) mod number of buckets. Going straight to the right bucket, instead of searching, is what makes lookups fast.

On average, inserting, finding and deleting a key in a hash table are all O(1). That's why hash tables, called dictionaries, maps or objects in different languages, are probably the most used data structure in everyday programming. JavaScript provides Map for key-value pairs and Set for collections of unique values; Python has dict and set; Java has HashMap and HashSet.

The word average matters. Understanding why it's average, and what can go wrong, is the rest of this lesson.

Step 2 of 11Practice · True or false

Hash table lookups are O(1) even in the worst case, no matter how keys are distributed.

Step 3 of 11Learn

Hash functions and collisions

A good hash function has three properties:

  • Deterministic: the same key always gives the same hash, or you'd never find anything again.
  • Fast to compute.
  • Uniform: it spreads keys evenly across buckets, so similar keys like user1 and user2 end up far apart.

No matter how good the function is, collisions, two different keys landing in the same bucket, are unavoidable. There are infinitely many possible keys and only so many buckets. Collisions also come sooner than intuition suggests: by the birthday paradox, with 365 buckets, there's a better than even chance of a collision after just 23 keys.

There are two main ways to handle collisions:

  • Separate chaining: each bucket holds a small list of entries. A lookup hashes to the bucket, then searches its short list. If keys are spread evenly, each list stays tiny.
  • Open addressing: all entries live directly in the array. When a bucket is taken, the table probes for another slot, for example the next one along in linear probing. A lookup follows the same probe sequence until it finds the key or an empty slot.

Either way, performance depends on keeping buckets lightly filled. If a poor hash function sends many keys to the same few buckets, chains grow long or probe sequences get long, and lookups degrade toward O(n). Attackers have even exploited weak hash functions in web servers by sending crafted keys that all collide, which is why many languages randomize their hash functions.

A hash table with separate chaining: keys are hashed to bucket indices, and colliding keys share a chain"apple"hash → 1"kiwi"hash → 3"grape"hash → 1"melon"hash → 401234apple → grapekiwimelonbuckets"apple" and "grape" collide in bucket 1 and share a chain

Step 4 of 11Practice · Work it out

A hash table using separate chaining has 800 buckets and stores 600 entries. What is its load factor?

Step 5 of 11Learn

Load factor and resizing

The load factor is the number of entries divided by the number of buckets. With chaining, it's the average chain length. As it grows, collisions become more frequent and operations slow down; with open addressing, performance falls off sharply as the table approaches full.

To keep operations fast, hash tables resize: when the load factor passes a threshold, often around 0.75, the table allocates a larger bucket array, typically double the size, and rehashes every entry into it, because each key's index depends on the number of buckets. Rehashing costs O(n), but like dynamic array growth, it happens rarely enough that inserts are amortized O(1).

A few practical rules for using hash tables well:

  • Keys must not change while they're in the table. If a key's hash changes after insertion, the table looks in the wrong bucket. That's why Python only allows immutable types like strings, numbers and tuples as dict keys.
  • Order isn't guaranteed in a classic hash table. JavaScript's Map and modern Python dicts happen to preserve insertion order, but you can't get keys in sorted order without sorting them yourself, which is O(n log n). If you need sorted keys, a balanced search tree is a better fit.
  • Hash tables use extra memory for empty buckets and bookkeeping.
  • In JavaScript, prefer Map over plain objects for arbitrary keys: Map accepts any key type, has a size property, and avoids clashes with built-in property names.

Step 6 of 11Try the calculator

Load factor and resizing

Enter how many entries and buckets a hash table has. If the load factor passes the threshold, the table doubles its buckets until it is back under.

Load factor (average chain length)
0.75
Doublings needed
0
Buckets after resizing
800

Step 7 of 11Practice · Code challenge

Write twoSum(nums, target) that returns an array [i, j] with i < j of the indices of two numbers that add up to target, using a single pass and a Map. Each test has exactly one answer.

Runs in a sandbox in your browser.
  • twoSum([2, 7, 11, 15], 9)
  • twoSum([3, 2, 4], 6)
  • twoSum([3, 3], 6)
  • twoSum([1, 5, 9, 14, 20], 29)
  • twoSum([-4, 8, 1, 6], 2)

Step 8 of 11Learn

Patterns that use hash tables

Once you know hash tables give average O(1) lookups, you'll see them as the key to many problems. The most common patterns:

  • Seen-before checks: use a Set to detect duplicates or the first repeated element in one pass. Have I seen this already? becomes an O(1) question.
  • Counting: use a Map from item to count to find word frequencies, the most common element, or whether two strings are anagrams (same letter counts).
  • Complement lookup: as in two-sum, store what you've seen and look up what you need.
  • Grouping: map a computed key to a list of items, such as grouping words by their sorted letters to collect anagrams, or grouping orders by customer.
  • Indexing: build a Map from ID to object once, in O(n), so later lookups by ID are O(1) instead of searching an array each time.
  • Caching and memoization: store results of expensive function calls keyed by their inputs, so repeated calls return instantly. You'll use this in dynamic programming.

The trade-off is almost always memory for time: O(n) extra space to bring the running time from O(n²) or O(n log n) down to O(n). That's usually a great deal, but not always; for small inputs, or when memory is very tight, a simple nested loop or sorting first may be the better choice.

Six hash table patternsHash table patternsSeenbeforeCountingComple-mentGroupingIndexingCaching

Step 9 of 11Practice · Match the pairs

Match each problem to the hash table pattern that solves it in O(n).

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Find the first repeated character in a string
  2. Find the most frequent word in a document
  3. Group words that are anagrams of each other
  4. Look up customer records by ID many times
  5. Avoid recomputing an expensive function for repeated inputs

Step 10 of 11Note

Step 11 of 11Practice · Choose one

Why does using a hash set make checking an array of n items for duplicates O(n) instead of O(n²)?