๐ช Hash-Based Design: Building Smart Storage Systems
Imagine youโre the manager of a magical library. Not just any libraryโone where books can appear, disappear, and you need to remember which ones people read most recently. Today, weโll learn how to build three amazing storage systems using the power of hash tables!
๐ Our Everyday Metaphor: The Smart Locker System
Think of a hash table like a wall of smart lockers at a gym:
- Each locker has a number (the key)
- Inside is your stuff (the value)
- A special robot helper (hash function) tells you exactly which locker to use
Now letโs build three incredible systems!
๐ฆ 1. Design HashMap: Your Personal Locker Wall
What is a HashMap?
A HashMap is like having your own wall of lockers where:
- You pick a name for each locker (key)
- You put anything you want inside (value)
- The robot instantly knows which locker matches which name
Simple Example:
๐ "apple" โ ๐๏ธ Locker #3 โ ๐ Price: $2
๐ "banana" โ ๐๏ธ Locker #7 โ ๐ Price: $1
๐ "orange" โ ๐๏ธ Locker #3 โ ๐ฅ Collision!
The Collision Problem ๐ฅ
Sometimes two keys want the same locker! This is called a collision.
Solution: Chaining ๐ Each locker can hold a small chain of items:
Locker #3: [appleโ$2] โ [orangeโ$3]
Building Our HashMap
class MyHashMap {
constructor() {
this.size = 1000;
this.buckets = new Array(this.size)
.fill(null)
.map(() => []);
}
// Robot helper picks locker
_hash(key) {
return key % this.size;
}
// Put item in locker
put(key, value) {
const idx = this._hash(key);
const bucket = this.buckets[idx];
for (let pair of bucket) {
if (pair[0] === key) {
pair[1] = value; // Update
return;
}
}
bucket.push([key, value]); // New
}
// Find item in locker
get(key) {
const idx = this._hash(key);
for (let pair of this.buckets[idx]) {
if (pair[0] === key) return pair[1];
}
return -1; // Not found
}
// Remove from locker
remove(key) {
const idx = this._hash(key);
const bucket = this.buckets[idx];
const i = bucket.findIndex(p => p[0] === key);
if (i !== -1) bucket.splice(i, 1);
}
}
Real Life Example ๐ฎ
const prices = new MyHashMap();
prices.put(1, 100); // Item #1 costs $100
prices.put(2, 200); // Item #2 costs $200
prices.get(1); // Returns 100
prices.remove(2); // Bye bye item #2
prices.get(2); // Returns -1 (gone!)
๐ฏ 2. Design HashSet: The Guest List
What is a HashSet?
A HashSet is like a bouncerโs guest list at a party:
- Names onlyโno extra info
- Each name appears only once
- Quick check: โIs this person on the list?โ
Simple Example:
Guest List: { "Alice", "Bob", "Charlie" }
โ
"Is Alice invited?" โ YES!
โ "Is Dave invited?" โ NO!
Building Our HashSet
class MyHashSet {
constructor() {
this.size = 1000;
this.buckets = new Array(this.size)
.fill(null)
.map(() => []);
}
_hash(key) {
return key % this.size;
}
// Add guest to list
add(key) {
if (!this.contains(key)) {
this.buckets[this._hash(key)].push(key);
}
}
// Remove guest
remove(key) {
const bucket = this.buckets[this._hash(key)];
const idx = bucket.indexOf(key);
if (idx !== -1) bucket.splice(idx, 1);
}
// Check if invited
contains(key) {
return this.buckets[this._hash(key)]
.includes(key);
}
}
Real Life Example ๐
const guests = new MyHashSet();
guests.add(1); // Guest #1 invited
guests.add(2); // Guest #2 invited
guests.contains(1); // true - welcome!
guests.remove(2); // Guest #2 uninvited
guests.contains(2); // false - sorry!
๐ 3. LRU Cache: The VIP Memory System
What is an LRU Cache?
LRU = Least Recently Used
Imagine your brain can only remember 5 phone numbers. When you learn a new one, you forget the one you havenโt used in the longest time!
Simple Example:
Memory capacity: 3 items
Add "Mom" โ [Mom]
Add "Dad" โ [Dad, Mom]
Add "Friend" โ [Friend, Dad, Mom]
Add "Boss" โ [Boss, Friend, Dad] ๐จ Mom forgotten!
Use "Dad" โ [Dad, Boss, Friend]
(Dad moves to front!)
The Magic Combo ๐ช
LRU Cache uses two data structures together:
graph TD A["HashMap"] -->|O 1 lookup| B["Find item instantly"] C["Doubly Linked List"] -->|O 1 reorder| D["Move items easily"] B --> E["๐ Fast cache!"] D --> E
- HashMap: Find any item in O(1)
- Doubly Linked List: Move items around in O(1)
Building Our LRU Cache
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map(); // HashMap!
// Map keeps insertion order
// in JavaScript
}
get(key) {
if (!this.cache.has(key)) return -1;
// Move to "recently used"
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
put(key, value) {
// If exists, remove first
if (this.cache.has(key)) {
this.cache.delete(key);
}
// Add as most recent
this.cache.set(key, value);
// Too full? Remove oldest
if (this.cache.size > this.capacity) {
// First key = oldest
const oldest = this.cache.keys().next().value;
this.cache.delete(oldest);
}
}
}
Real Life Example ๐ง
const browser = new LRUCache(3);
browser.put(1, "google.com");
browser.put(2, "youtube.com");
browser.put(3, "github.com");
// Cache: [1, 2, 3]
browser.get(1); // Returns "google.com"
// Cache: [2, 3, 1] - google moved to end!
browser.put(4, "twitter.com");
// Cache: [3, 1, 4] - youtube evicted!
browser.get(2); // Returns -1 (evicted!)
๐จ The Big Picture
graph LR H["Hash Table Magic"] --> A["HashMap"] H --> B["HashSet"] H --> C["LRU Cache"] A --> A1["KeyโValue pairs"] A --> A2["put/get/remove"] B --> B1["Keys only"] B --> B2["add/contains/remove"] C --> C1["Limited memory"] C --> C2["Evicts least used"]
๐ก Why Does This Matter?
| Structure | Use Whenโฆ | Real Example |
|---|---|---|
| HashMap | Store key-value pairs | Phone contacts |
| HashSet | Track unique items | Visited websites |
| LRU Cache | Limited fast memory | Browser cache |
๐ Key Takeaways
- HashMap = Lockers with names + stuff inside
- HashSet = Guest list (names only, no duplicates)
- LRU Cache = Smart brain that forgets old stuff
- Hash function = Robot that picks the right locker
- Collisions = When two keys want same locker (use chaining!)
๐ You Did It!
You now understand three powerful hash-based designs:
โ HashMap: Store anything with instant lookup โ HashSet: Track unique items efficiently โ LRU Cache: Smart memory that keeps recent items
These patterns power everything from databases to web browsers. Youโre thinking like a real engineer now! ๐
