15% off all plans & roadmaps Use code

See plans

Design HashMap

Updated

TL;DR: You must build a HashMap from scratch with put, get and remove, and no built-in hash table. Since keys and values stay between 0 and 10^6, you can index a flat array by the key itself.

Problem

Design a HashMap without using any built-in hash table library.

Implement the MyHashMap class:

  • MyHashMap() creates an object with an empty map.
  • void put(int key, int value) inserts a (key, value) pair. If the key already exists, it replaces the stored value.
  • int get(int key) returns the value mapped to key, or -1 if the map has no mapping for key.
  • void remove(key) deletes key and its value if the map contains a mapping for it.

Example 1

Input: ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output: [null, null, null, 1, -1, null, 1, null, -1]
Explanation:
- myHashMap.put(1, 1): the map is now [[1,1]].
- myHashMap.put(2, 2): the map is now [[1,1], [2,2]].
- myHashMap.get(1): returns 1.
- myHashMap.get(3): returns -1, because no mapping exists.
- myHashMap.put(2, 1): the map is now [[1,1], [2,1]], so the existing value is updated.
- myHashMap.get(2): returns 1.
- myHashMap.remove(2): the map is now [[1,1]].
- myHashMap.get(2): returns -1, because the mapping was removed.

Constraints

  • 0 <= key, value <= 10^6
  • At most 10^4 calls will be made to put, get, and remove.

Constraints that matter

  • Keys and values stay at or below 10^6, so a flat array of 10^6 + 1 slots can hold every key. That rules in direct addressing.
  • At most 10^4 calls means a full scan of up to 10^4 stored pairs can cost about 5 * 10^7 comparisons in total. That is correct but not the design the problem asks for.
  • Values are never negative, so -1 can mark a missing key without colliding with real data.
  • Built-in hash tables are banned, so you must write the index and the collision handling yourself.

View on LeetCode

Hints

Hint 1

Every call names a key, and the answer depends only on that key.

Hint 2

Keep every pair in one list.

Solution

Intuition

Every call names a key, and the answer depends only on that key. This is a keyed lookup problem. You want the time to find a key to stay flat as the map grows. Hashing does this by turning the key into an index, so you check one small spot instead of every stored pair.

Picture a row of numbered mailboxes, one for every key from 0 to 10^6. The array is that row, and the key is the box number, so you walk straight to the right box. An empty box holds a -1 slip, meaning no mapping is stored there.

The constraints decide which design fits. Keys go up to 10^6, so the key itself can serve as an array index. This is direct addressing. If keys were unbounded, you would hash them into buckets and resolve collisions with separate chaining. Both designs use the same API, so the choice comes down to the bounds.

Two things must hold. The same key must always map to the same place, so get finds what put wrote.

A missing key must produce -1 without a false match. The -1 sentinel covers this second rule because stored values are never negative. Each approach below meets both rules in a different way.

Watch the pattern animation

Worked example

Input: ["MyHashMap", "get", "remove", "get"]
[[], [999999], [999999], [999999]]
Output: [null, -1, null, -1]
Explanation: The map starts empty, so the first get(999999) returns -1. remove(999999) has nothing to delete, so it changes nothing. The last get(999999) still finds no mapping and returns -1. This example never calls put, so it only tests the missing-key path. The edge cases below cover stored keys.

Approach 1: Brute force list

Keep every pair in one list. put scans the list for the key. If it finds the key, it updates the value. If not, it appends a new pair. get and remove scan the list the same way.

This is correct, and it is the first design most people write. The cost is the scan. Each call walks past stored pairs until it finds the key or runs out of pairs.

Steps

  1. Create an empty list of [key, value] pairs.
  2. In put, check each pair. If one has the key, set its value and stop.
  3. If no pair matched, append [key, value] to the list.
  4. In get, check each pair. Return the value of the first match.
  5. If no pair matched, return -1.
  6. In remove, find the matching pair and delete it from the list.

Dry run

The list starts empty. get(999999) checks zero pairs, so it returns -1. remove(999999) checks zero pairs and removes nothing. The second get(999999) also checks zero pairs and returns -1. The output is [null, -1, null, -1], which matches the example.

Complexity

TimeO(n) per call
SpaceO(n)

Let n be the number of distinct keys stored at the moment of the call. put, get and remove each loop over the list once, and each step does constant work. Each key adds one pair, so the list holds at most n entries and the space is O(n). With at most 10^4 calls, n never exceeds 10^4.

PythonTested in our runner

from typing import List, Optional

class MyHashMap:
    def __init__(self):
        # Unordered list of [key, value] pairs
        self.pairs = []

    def put(self, key: int, value: int) -> None:
        for pair in self.pairs:
            if pair[0] == key:
                pair[1] = value
                return
        self.pairs.append([key, value])

    def get(self, key: int) -> int:
        for k, v in self.pairs:
            if k == key:
                return v
        return -1

    def remove(self, key: int) -> None:
        for i, (k, _) in enumerate(self.pairs):
            if k == key:
                self.pairs.pop(i)
                return

Approach 2: Separate chaining with hashed buckets

What's slow: every call scans all stored pairs, but only pairs with the same key can match. Most of that scanning is wasted.

The insight that fixes it is hashing. Pick a fixed bucket count B and send each key to bucket key % B. Keys that land in the same bucket share a short list, and a call scans only that list.

Collisions still happen, so each bucket is a chain of pairs. With B = 2069 and at most 10^4 keys, an average chain holds about five pairs.

Steps

  1. Create 2069 empty buckets. A prime bucket count avoids the regular gaps a power of two can create.
  2. Compute the bucket index as key % 2069.
  3. In put, scan that bucket. Update the value if the key is there, otherwise append [key, value].
  4. In get, scan only that bucket and return the matching value, or -1 if none matches.
  5. In remove, scan only that bucket and delete the matching pair.

Dry run

Compute the bucket for 999999. 2069 times 483 is 999327, so the bucket is 999999 - 999327 = 672. Bucket 672 is empty. get(999999) scans zero pairs and returns -1.

remove(999999) scans zero pairs and changes nothing. The second get(999999) returns -1 as well. The output is [null, -1, null, -1].

Complexity

TimeO(1) average, O(n) worst case
SpaceO(n + B), with B = 2069 fixed

Let n be the number of stored keys and B = 2069 the bucket count. A call computes one remainder and then scans one bucket, so its work equals that bucket's length. When keys spread evenly, each bucket holds about n / B pairs, which is at most about 5 here, a constant.

If every key lands in one bucket, a call scans all n pairs, so the worst case is O(n). The space is B bucket slots plus one entry per stored key.

PythonTested in our runner

from typing import List, Optional

class MyHashMap:
    def __init__(self):
        self.size = 2069  # prime bucket count
        # Each bucket is a list of [key, value] pairs
        self.buckets = [[] for _ in range(self.size)]

    def _bucket(self, key: int) -> list:
        return self.buckets[key % self.size]

    def put(self, key: int, value: int) -> None:
        bucket = self._bucket(key)
        for pair in bucket:
            if pair[0] == key:
                pair[1] = value
                return
        bucket.append([key, value])

    def get(self, key: int) -> int:
        for k, v in self._bucket(key):
            if k == key:
                return v
        return -1

    def remove(self, key: int) -> None:
        bucket = self._bucket(key)
        for i, pair in enumerate(bucket):
            if pair[0] == key:
                bucket.pop(i)
                return

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 3: Direct addressing arrayOptimalDesign (General/Specific)

What's slow: chaining is fast on average, but its speed depends on how keys spread across buckets. Keys that share a bucket force a scan, and an unlucky key set makes every call scan everything.

The insight that fixes it is that the key range is known. Keys are integers from 0 to 10^6, so the key can be the index itself. Store each value at values[key]. Then put, get and remove each touch one slot, and no hashing or scanning is needed.

Empty slots need a marker. Stored values are never negative, so -1 can mean no mapping. The constructor fills every slot with -1.

This design depends on the small bounds. For unbounded keys, use chaining.

Why it is correct. The invariant is that values[k] always holds the latest value written for key k, or -1 if no mapping is active. Each key owns its own index, so a write to one key never touches another key's slot. Stored values are never negative, so a -1 can only mean no mapping, and get never returns a false match.

Steps

  1. Allocate an array of 1000001 integers, one slot for each key from 0 to 10^6.
  2. Fill every slot with -1, which means no mapping.
  3. In put, set values[key] = value.
  4. In get, return values[key]. A missing key holds -1, so no separate check is needed.
  5. In remove, set values[key] = -1 to clear the mapping.

Dry run

The table traces the verified example. The array index is 999999, and every other slot stays -1.

StepCallvalues[999999] beforevalues[999999] afterReturn
0constructornone-1null
1get(999999)-1-1-1
2remove(999999)-1-1null
3get(999999)-1-1-1

The returned values are null, -1, null, -1, which match the expected output.

Complexity

TimeO(1) per call, worst case. The constructor takes O(10^6) once.
SpaceO(10^6), a fixed array of 1000001 slots

Each method performs one array read or one array write, so its work does not depend on how many pairs are stored. Let C = 10^6 be the largest key. The constructor writes C + 1 slots once, which is a fixed cost. The array never grows, so the space is O(C), a constant for these bounds, and it does not depend on n.

PythonTested in our runner

from typing import List, Optional

class MyHashMap:
    def __init__(self):
        # Keys go up to 10^6. Stored values are never negative, so -1 marks an empty slot.
        self.values = [-1] * 1000001

    def put(self, key: int, value: int) -> None:
        self.values[key] = value

    def get(self, key: int) -> int:
        return self.values[key]

    def remove(self, key: int) -> None:
        self.values[key] = -1

Common mistakes

  • The constructor leaves the array at its default 0, for example values = new int[N] in Java with no fill. A missing key then returns 0 instead of -1. Fill the array with -1 in the constructor.
  • bucket.append([key, value]) runs before the scan for an existing key. The same key then appears twice, and get returns the older value. Scan the bucket first, update on a match, and append only when nothing matched.
  • if curr.key == key checked only at the head, followed by a return. Keys further down the chain are never found or removed. Walk the whole chain and unlink the matching node, including when it is the head.
  • curr.key read after the loop has moved curr to null. This crashes on an empty bucket. Check that the bucket is non-empty before you read a node's fields.
  • key % SIZE with a negative key gives a negative index in Java and C#. The constraints rule this out, but a wider key range needs Math.floorMod(key, SIZE).
  • remove that skips values[key] = -1 in the direct array leaves the old value in place, so get still returns it. Write -1 back to clear the mapping.

Edge cases

  • Empty map: get(0) returns -1 because nothing is stored yet.
  • Stored value 0: put(5, 0) followed by get(5) returns 0, not -1. The sentinel must never be a legal value.
  • Keys sharing a bucket: put(0, 7) and put(2069, 8) both land in bucket 0 when chaining. get(2069) returns 8 and get(0) returns 7.
  • Duplicate put: put(2, 2) and then put(2, 1). get(2) returns 1, and the map holds only one entry for key 2.
  • Maximum key: put(1000000, 3) followed by get(1000000) returns 3. The direct array needs index 1000000, so its size must be 1000001.
  • Removing a missing key: remove(42) changes nothing, and get(42) still returns -1.

Follow-ups interviewers ask

What if keys can be any 32-bit integer?
Direct addressing would need about 4 billion slots, which is not practical. Use separate chaining instead. Resize the bucket array when the average chain grows past about 0.75 pairs per bucket, and rehash every stored pair into the new array. Use a non-negative remainder for negative keys, such as Math.floorMod in Java.
What if several threads call put and get at the same time?
The brute force list needs one lock around the whole list. Chaining lets you lock each bucket separately, so calls on different buckets do not wait for each other. The direct array can lock each slot or use atomic integers, but a single key's update must stay in one atomic step.
What if the 1000001-slot array uses too much memory?
With at most 10^4 calls, at most 10^4 keys are stored. Chaining uses memory for the stored pairs plus 2069 bucket slots, far less than the direct array. The cost is that the time bound becomes an average, not a guarantee.

Design HashMap FAQ

What is the time complexity of Design HashMap?

Direct addressing gives O(1) per call in the worst case, after a one-time O(10^6) constructor. Separate chaining gives O(1) average per call and O(n) in the worst case. The brute force list costs O(n) per call.

Why use hashing for Design HashMap?

Hashing turns a key into a bucket index in constant time. Each call then scans one short bucket instead of every stored pair. With a fixed bucket count B, that cuts the work from n to about n / B.

Can Design HashMap be solved in O(1) extra space?

No. A map that stores n pairs must keep at least n values, so memory grows with n. The direct array uses a fixed 1000001 slots, which is a constant for these bounds, so its size does not grow with the number of calls.

Is removing from a Python list O(1)?

Only at the end. Calling pop() on the last index is O(1). Calling pop(i) in the middle shifts later items left, which costs time proportional to the list length. In the chaining version that length is one bucket, which stays short.

Why does get return -1 for a missing key?

The problem defines -1 as the answer for a missing key. Values are never negative here, so -1 cannot be a real stored value. The direct array depends on this to mark empty slots.

Asked at

See which companies ask this — Pro

Practise it