Stop 21 · Data Structures & AlgorithmsTopics · 6/17

HashMap

Part of the Frontend Developer Roadmap

In short

If you remember only one interview trick, make it this: when a brute force needs a second loop to find something, a HashMap can usually find it in one step instead.

A key-value data structure offering average O(1) lookup, insert and delete — arguably the single most useful tool for optimizing brute-force solutions to O(n).

The jaadu points at an entry in a hostel register while holding up a room key.

Think of it like this

The hostel warden's register

Ask the warden 'which room is Rahul in?' and they don't knock on every door. They look up the name in the register and answer straight away. A HashMap is that register for your data.

Watch it happen

Two Sum with target 9

11
0
i
2
1
15
2
7
3

1/4x = 11, so we need 9 - 11 = -2. Not in the Map, so store 11 → 0.

The big ideas

What you need to know

Key goes in, value comes out

get, set, has and delete are O(1) on average, whatever the size.

Prefer Map over a plain object

Map keeps any key type, keeps insertion order and has a size property. Objects turn keys into strings.

Set for 'have I seen this?'

When you need only keys, a Set is a HashMap without values.

You pay with memory

The speed comes from storing extra data, so space usually goes up to O(n).

See it in code

Walk through the code

js
1function twoSum(nums, target) {2  const seen = new Map(); // value -> index3 4  for (let i = 0; i < nums.length; i++) {5    const need = target - nums[i];6    if (seen.has(need)) return [seen.get(need), i];7    seen.set(nums[i], i);8  }9  return [];10}11 12twoSum([2, 7, 11, 15], 9); // [0, 1]

1/4The Map remembers each value we've seen and its index.

One loop with O(1) Map lookups gives O(n) time. The Map may store every number, so space is O(n). The two-loop brute force is O(n²).

Save yourself the pain

Common mistakes

Oops

Using an object with obj[key] and getting '1' and 1 treated as the same key.

Do this instead

Use a Map when keys might be numbers or objects. It keeps their real type.

Oops

Saying HashMap lookup is always O(1).

Do this instead

Say 'O(1) on average'. With many collisions it can get worse, and interviewers like hearing you know that.

Your mission

HashMap hat-trick

~40 min

Quick check

Why does the HashMap version of Two Sum beat the two-loop version?

Go deeper

  1. 1Solve two-sum using a hash map and compare it to the O(n²) brute-force approach.
  2. 2Practice using a hash map to count frequencies (anagrams, duplicates).
  3. 3Learn how hash maps achieve near-constant-time lookups under the hood (hashing + buckets).

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge