DSA Basics: Hash Map

Learn hash maps for fast lookup, counting, grouping, and classic two-sum style problems.

Back to Learn DSA

A hash map stores key-value pairs and gives fast access by key.

In JavaScript, Map is a good general-purpose hash map. Plain objects can also work, but Map avoids many edge cases around inherited keys.

Basic usage

const counts = new Map();

for (const value of values) {
	counts.set(value, (counts.get(value) ?? 0) + 1);
}

This code counts how many times each value appears.

Why hash maps matter

Many slow nested-loop solutions become faster when you store information in a hash map.

Example: two sum.

function twoSum(values, target) {
	const seen = new Map();

	for (let i = 0; i < values.length; i++) {
		const needed = target - values[i];

		if (seen.has(needed)) {
			return [seen.get(needed), i];
		}

		seen.set(values[i], i);
	}

	return [];
}

Common uses

Complexity

Hash map operations are usually O(1) on average, but can degrade if many keys collide. For interview and practice problems, average O(1) is usually assumed.

Practice problems

  1. Two sum.
  2. First non-repeating character.
  3. Group anagrams.
  4. Contains duplicate.
  5. Count pairs with a given difference.

Interactive walkthrough

Hash Map Visualizer

Track values as keys for fast lookup and counting.
Step 1 key
Step 2 value
Step 3 seen
Step 4 count