Interactive Lab: Build Your Own Hash Table
add_circle Insert Data
search Lookup / Search
Quick Presets (Try these!)
Under the Hood
We are using a very simple hash function for this demo:
Waiting for input...
Memory Array (Buckets)
How It Works
Imagine a massive library. Usually, to find a book, you'd check a catalog, find the aisle, find the shelf, then scan the books (Time: O(log n) or O(n)).
A Hash Table is different. You give the librarian the book title, and they perform a magical math calculation (the Hash Function) that tells them: "This book belongs exactly on Shelf 4, Slot 2." They walk directly there. No searching.
The Process
- Key Input: You provide a key (e.g., "username").
- Hashing: The key is converted into an integer (hash code) using a deterministic algorithm.
- Modulo: The hash code is compressed to fit the array size (e.g., `hash % size`).
- Access: This resulting number is the direct index in memory.
The Problem: Collisions
What if two different keys (like "cat" and "act") result in the same index? This is called a Collision.
The demo above uses a strategy called Chaining. Notice how multiple items can live in the same bucket? The bucket becomes a Linked List.
- Best Case (No Collisions): O(1) - Instant access.
- Worst Case (All Collisions): O(n) - The table degrades into a single linked list, and you have to scan every item.
code Simple Implementation (JavaScript)
hashtable.jsclass HashTable {
constructor(size = 50) {
this.buckets = new Array(size);
this.size = size;
}
hash(key) {
let total = 0;
for (let i = 0; i < key.length; i++) {
total += key.charCodeAt(i);
}
return total % this.size;
}
set(key, value) {
let index = this.hash(key);
if (!this.buckets[index]) {
this.buckets[index] = [];
}
// Handle updates or push new
this.buckets[index].push([key, value]);
}
get(key) {
let index = this.hash(key);
if (!this.buckets[index]) return null;
// Search the chain (collision handling)
for (let bucket of this.buckets[index]) {
if (bucket[0] === key) {
return bucket[1];
}
}
return null;
}
}