data structures algorithms30 min

Hash Maps

Fast key-value lookups using hash functions

0/9Not Started

Why This Matters

Imagine you have a list of a million users and you need to find one by their username. With an array, you'd have to check each element one by one — potentially all million. A hash map does the same lookup almost instantly. It maps a key (like a username) to a value (like a user object) using a hash function that converts the key into an array index in constant time.

Hash maps are behind dictionaries, caches, database indexes, and virtually every fast-lookup system in software. Mastering them is essential for writing efficient code and solving interview problems.

Define Terms

Visual Model

"alice"
"bob"
"carol"
hash()key → index
[0] → alice:95
[1] → bob:87
[2] → carol:91
[3] (empty)
0
1
2

The full process at a glance. Click Start tour to walk through each step.

A hash map: the hash function maps keys to bucket indices for O(1) average-case access.

Code Example

Code
// Creating a hash map (using Map or plain object)
const userAges = new Map();
userAges.set("alice", 28);
userAges.set("bob", 34);
userAges.set("charlie", 22);

// O(1) lookup
console.log(userAges.get("bob"));     // 34
console.log(userAges.has("diana"));   // false
console.log(userAges.size);           // 3

// Frequency counting — a classic hash map pattern
function countFrequency(arr) {
  const freq = new Map();
  for (const item of arr) {
    freq.set(item, (freq.get(item) || 0) + 1);
  }
  return freq;
}

const words = ["apple", "banana", "apple", "cherry", "banana", "apple"];
console.log(countFrequency(words));
// Map { "apple" => 3, "banana" => 2, "cherry" => 1 }

// Two-sum problem using a hash map
function twoSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (seen.has(complement)) {
      return [seen.get(complement), i];
    }
    seen.set(nums[i], i);
  }
  return [];
}

console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]

Interactive Experiment

Try these exercises:

  • Build a frequency counter for the letters in your name. Which letter appears most?
  • Solve the two-sum problem for [3, 2, 4] with target 6 by tracing through the hash map by hand.
  • What happens if you insert the same key twice? Does it overwrite or create a duplicate?
  • Compare the time to look up an element in a Map vs. searching through an array with indexOf. Which is faster for 10,000 elements?

Quick Quiz

Coding Challenge

First Non-Repeating Character

Write a function called `firstNonRepeating` that takes a string and returns the first character that does not repeat anywhere in the string. If every character repeats, return an empty string. Use a hash map for an efficient O(n) solution.

Loading editor...

Real-World Usage

Hash maps are one of the most frequently used data structures in production:

  • Caching: Store computed results keyed by input to avoid recalculation (memoization)
  • Database indexing: Indexes map column values to row locations for fast queries
  • HTTP headers: Request and response headers are key-value pairs parsed into hash maps
  • Configuration: Environment variables and settings files are loaded into dictionaries
  • Deduplication: Track seen items to detect or remove duplicates in O(n)
  • Routing: Web frameworks map URL patterns to handler functions

Connections