Chapter 8 · Hash Structures

Hash Maps

The most powerful general-purpose data structure ever invented. Average O(1) insert, delete, and lookup — regardless of how many items you store. Understanding hash maps separates novice from experienced engineers.

What is a hash map?

A hash map (hash table) stores key–value pairs and finds any value by its key in O(1) on average. It hashes the key to an array index, so it doesn't need to search. In JavaScript, use Map (any key type, keeps insertion order) or a plain object for string keys. Hash maps are the single most useful structure in interviews: counting, caching, deduplication and lookups.

const ages = new Map();
ages.set("Ada", 36);
ages.get("Ada");          // 36   O(1) average
ages.has("Bob");          // false
ages.delete("Ada");

// Two Sum in O(n) with a hash map
function twoSum(nums, target) {
  const seen = new Map();
  for (const [i, n] of nums.entries()) {
    if (seen.has(target - n)) return [seen.get(target - n), i];
    seen.set(n, i);
  }
}

The core idea

Arrays give O(1) access by integer index. A hash map extends that to any key type — strings, objects, anything — by transforming the key into an integer index via a hash function.

Your key

"username"
hash()

Integer index

42
% buckets

Bucket

[2]
🔍Why this achieves O(1)
Once the index is computed, reading from bucket[2] is an array access — O(1). The hash function runs in constant time (it only looks at the key, not all stored keys). So the total cost is O(1) + O(1) = O(1).
0 ns

Average lookup regardless of stored count

0%

Typical maximum load factor before resize

0x

Capacity multiplier on resize (like dynamic arrays)

Live demo — hash, bucket, and collision

Type a key and value then hit Set. Watch which bucket the hash function selects and see collisions appear when two keys land in the same slot.

Hash Map — 8 buckets · h(k) = polyHash(k) % 8

entries: 0
[0]
—
[1]
—
[2]
—
[3]
—
[4]
—
[5]
—
[6]
—
[7]
—

Interactive sandbox — code a Hash Map

Implement a rolling hash algorithm and chain-based collision resolution using singly linked nodes. Insert, delete, and lookup keys instantly!

Code Editor

<input id="k" placeholder="key" value="apple">
<input id="v" placeholder="value" value="1.99">
<button id="set">set</button> <button id="get">get</button> <button id="del">delete</button>
<pre id="out"></pre>

Preview

Code playground — build it yourself

Test separate chaining manually. This implementation splits your collisions directly into array lists underneath bucket addresses:

Code Editor

<pre id="out"></pre>

Preview

Core operations

hash-map.pseudo
1HashMap: array of buckets, each bucket is a list of (key, value) pairs
2 
3put(key, value):
4 index <- hash(key) % buckets.length
5 for each pair in buckets[index]:
6 if pair.key = key: pair.value <- value; return // update
7 buckets[index].append((key, value)) // insert
8 if load_factor() > 0.75: resize(capacity x 2)
9 
10get(key):
11 index <- hash(key) % buckets.length
12 for each pair in buckets[index]:
13 if pair.key = key: return pair.value
14 return null // not found
15 
16delete(key):
17 index <- hash(key) % buckets.length
18 remove pair where pair.key = key from buckets[index]

Collision resolution

Two different keys can produce the same index. This is called a collision, and every hash map must handle it. There are two dominant strategies:

Separate chaining

Java HashMap, Python dict (legacy)

Each bucket holds a linked list. Colliding entries are appended to the list. Lookup scans the list. Simple and handles high load factors gracefully.

Open addressing (linear probing)

Python dict (modern), many embedded systems

When a collision occurs, search the next empty slot. Lookup follows the same probe sequence. Cache-friendly but degrades under high load (clustering).

Load factor and resizing

Load factor = items stored / total buckets. As load factor grows, collisions increase and performance degrades. Most implementations resize (double capacity) when load factor exceeds 0.75.

0.25
0.50
0.75
1.00+

Time complexity

Get by key (average)O(1)

Constant time

Put / insert (average, amortized)O(1)

Constant time

Delete by key (average)O(1)

Constant time

Get / put (worst case — all keys collide)O(n)

Linear time

Iterate all entriesO(n)

Linear time

⚠️Average vs worst case
Hash maps promise O(1) average, not worst case. A deliberately crafted set of keys that all hash to the same bucket degrades lookup to O(n). Cryptographic hash functions in modern implementations make this attack computationally infeasible.

🎯 Quick Check

You insert 100 items into a hash map with 128 buckets. Load factor reaches ~0.78, triggering a resize to 256 buckets. What happens to existing keys during resize?

🧠When to reach for a hash map
Any time you need to look something up by an arbitrary key and O(1) average matters more than sorted order — use a hash map. Frequency counting, deduplication, memoization, grouping — these are all hash map problems.

Hash Maps: summary

Key points

  • Average O(1) for get, set and delete; the worst case is O(n) when many keys collide.
  • Prefer Map over objects for frequent additions and removals, or for non-string keys.
  • Replacing a nested loop with a hash map lookup often turns O(n²) into O(n).

Frequently asked questions

›Map vs object in JavaScript?

Map accepts any key type, keeps insertion order, has .size, and is optimised for frequent changes. Objects are fine for fixed records with string keys and JSON.

›Why is hash map lookup O(1)?

The key is hashed directly to an array index, so the map jumps to the right bucket instead of scanning entries.