Kazi Rahamatullah
Kazi Rahamatullah
AboutProjectsBlogContact
UsesBooks
ResumeView CV
Kazi Rahamatullah

© Copyright 2026 Kazi Rahamatullah

AboutProjectsBlogBooksUses
Twitter/XGitHubProduct HuntCodeSandbox
Back to Blog
DSAHash TablesHash MapsData Structures

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.

Jul 4, 20264 min read

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
1Map vs object
2Interactive visualizer
3Full implementation
4Patterns & use cases
5Real-life examples

1. Map vs object

FeatureJS Object {}Hash Map
Key typesString/Symbol onlyAny hashable type
Iteration orderNot guaranteed (legacy)Insertion order
SizeManual countO(1) .size
PerformanceGood for small/staticOptimized for frequent updates
plaintext
cache.set("user:42", { name: "Alice" })
cache.get("user:42")  →  { name: "Alice" }

Back to index


2. Interactive visualizer

Hash Maps — Key-Value Store

Key → value pairs with O(1) average get, set, and delete — foundation of caches and dictionaries.

[0]
empty
[1]
empty
[2]
empty
[3]
empty
[4]
empty
[5]
empty
[6]
empty
Capacity: 7Load: 0/7Type: Map

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

Back to index


3. Full implementation

js
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

js
// ── 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') // → 2

Back to index


4. Patterns & use cases

PatternExample
Cache / memoizationfn(args) → result stored by key
Frequency countWord → occurrence count
GroupingCategory → list of items
Two-sumComplement → index stored

Interview Answer

"How does a hash map achieve O(1) lookup?"

Hash the key to a bucket index in O(key length), then read that bucket. With a good hash and low load factor, the bucket has O(1) entries — total average O(1).

Back to index


5. Real-life examples

ScenarioHash map role
RedisKey → string/value in memory
React propsProp name → value passed to component
Env variablesprocess.env.KEY → value
MemoizationFunction 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.

Back to index


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

Share this article

XLinkedInFacebook
Kazi Rahamatullah

Written by

Kazi Rahamatullah

FullStack Developer

X / TwitterGitHubLinkedIn

Subscribe to my newsletter

Stay up to date and get notified when I share new contents.

No spam ever, unsubscribe anytime