DSA Hash Maps — Key-Value Store Visualized
Learn hash maps — O(1) get/set/delete on key-value pairs, cache patterns, interactive bucket visualizer, and dictionary use cases.
Introduction
Hash maps store key → value pairs with O(1) average lookup — the most used associative
structure in programming. JavaScript Map, Python dict, and Redis all build on this.
Built on hash table fundamentals, maps add the value layer that hash sets omit.
Quick index
| # | Section |
|---|---|
| 1 | Map vs object |
| 2 | Interactive visualizer |
| 3 | Full implementation |
| 4 | Patterns & use cases |
| 5 | Real-life examples |
1. Map vs object
| Feature | JS Object {} | Hash Map |
|---|---|---|
| Key types | String/Symbol only | Any hashable type |
| Iteration order | Not guaranteed (legacy) | Insertion order |
| Size | Manual count | O(1) .size |
| Performance | Good for small/static | Optimized for frequent updates |
cache.set("user:42", { name: "Alice" })
cache.get("user:42") → { name: "Alice" }2. Interactive visualizer
Hash Maps — Key-Value Store
Key → value pairs with O(1) average get, set, and delete — foundation of caches and dictionaries.
Hash map stores key → value pairs — the core of JS Map and Python dict.
HashMap class
class HashMap {
set(key, value) { /* hash → bucket → store pair */ }
get(key) { /* hash → bucket → find key */ }
delete(key) { /* remove pair from chain */ }
}Map = hash table with key-value entries.
get / set
O(1) avg
Keys
Any hashable
Use case
Cache
3. Full implementation
class HashMap {
constructor(capacity = 7) {
this.capacity = capacity
this.buckets = Array.from({ length: capacity }, () => [])
this.count = 0
}
_hash(key) {
const str = String(key)
let hash = 0
for (let i = 0; i < str.length; i++) {
hash = (hash + str.charCodeAt(i) * (i + 1)) % this.capacity
}
return hash
}
set(key, value) {
const index = this._hash(key)
const bucket = this.buckets[index]
const existing = bucket.find((e) => e.key === key)
if (existing) {
existing.value = value
} else {
bucket.push({ key, value })
this.count++
}
return this
}
get(key) {
const bucket = this.buckets[this._hash(key)]
return bucket.find((e) => e.key === key)?.value
}
has(key) {
return this.get(key) !== undefined
}
delete(key) {
const index = this._hash(key)
const bucket = this.buckets[index]
const idx = bucket.findIndex((e) => e.key === key)
if (idx === -1) return false
bucket.splice(idx, 1)
this.count--
return true
}
keys() {
return this.buckets.flatMap((b) => b.map((e) => e.key))
}
size() {
return this.count
}
}
function wordFrequency(text) {
const map = new HashMap()
for (const word of text.toLowerCase().split(/\s+/)) {
map.set(word, (map.get(word) ?? 0) + 1)
}
return map
}Function calls with output
// ── Demo calls — output shown on the right ──
const cache = new HashMap()
cache.set('user:42', { name: 'Alice' }) // → stored
cache.set('user:99', { name: 'Bob' }) // → stored
cache.get('user:42') // → { name: 'Alice' }
cache.get('user:404') // → undefined
cache.has('user:99') // → true
cache.delete('user:99') // → true
cache.size() // → 1
wordFrequency('the cat and the hat').get('the') // → 24. Patterns & use cases
| Pattern | Example |
|---|---|
| Cache / memoization | fn(args) → result stored by key |
| Frequency count | Word → occurrence count |
| Grouping | Category → list of items |
| Two-sum | Complement → index stored |
5. Real-life examples
| Scenario | Hash map role |
|---|---|
| Redis | Key → string/value in memory |
| React props | Prop name → value passed to component |
| Env variables | process.env.KEY → value |
| Memoization | Function args → cached result |
In-memory API cache
Backend caches user profiles by ID — hash map avoids repeated database queries.
GET /users/42
cache.get(42) → undefined
→ query PostgreSQL (45ms)
First request hits database, stores result in map.
Real-world implementation
class UserCache {
constructor() { this.cache = new Map() }
async getUser(id) {
if (this.cache.has(id)) return this.cache.get(id)
const user = await db.users.find(id)
this.cache.set(id, user)
return user
}
}Full working code for the scenario above.
Function calls with output
| // ── Function calls with output ── | |
| cache.getUser(42) | → DB query → { id:42, name:"Alice" } |
Side output shows return value after each call — step through to trace execution.
Summary
Hash maps = O(1) average key → value access. The workhorse for caches, dictionaries, and frequency tables.
Next reads: Hash Tables · Hash Sets · Graph Traversal
Subscribe to my newsletter
Stay up to date and get notified when I share new contents.
No spam ever, unsubscribe anytime