Design HashMap

Easy

Topics
ArrayHash TableDesign

Design a HashMap without using any built-in hash table libraries. Implement MyHashMap with put(key, value), get(key) (returns the value or -1 if the key is absent), and remove(key).

Example 1

returnsMyHashMap()put(1, 1)put(2, 2)get(1)1get(3)-1put(2, 1)get(2)1remove(2)get(2)-1
Two details carry the contract: put on an existing key overwrites rather than appends, and get on a missing key returns -1 instead of failing.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["MyHashMap","put","put","get","get","put","get","remove","get"], values = [[],[1,1],[2,2],[1],[3],[2,1],[2],[2],[2]]
Output: [null,null,null,1,-1,null,1,null,-1]

Constraints

  • 0 <= key, value <= 10^6
  • At most 10^4 calls to put, get, and remove.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A hash map maps keys to values with O(1) average access. Bucket keys by a hash and store (key, value) pairs so collisions live in the same bucket and are scanned linearly.

Approach

  1. Keep an array of buckets; hash the key to pick a bucket.
  2. put scans the bucket to update an existing key or appends a new pair.
  3. get scans the bucket and returns the value or -1; remove deletes the pair.

Dry Run

MyHashMap()  --  1009 buckets, so the index is key % 1009
  put 1 1    -> null    bucket 1: [[1, 1]]
  put 2 2    -> null    bucket 1: [[1, 1]]   bucket 2: [[2, 2]]
  get 1      -> 1       scan bucket 1, find key 1
  get 3      -> -1      bucket 3 is empty; MISSING is -1, not 0
  put 2 1    -> null    bucket 2: [[2, 1]]   the pair is updated in place
  get 2      -> 1
  remove 2   -> null    bucket 2: []
  get 2      -> -1
answer null|null|null|1|-1|null|1|null|-1
The row to look at is "put 2 1". The bucket still holds one pair, not two: put
scans for the key first and overwrites p[1] when it finds it. Drop that scan and
just append, and bucket 2 becomes [[2, 2], [2, 1]] -- then get(2) returns 2,
because it stops at the first match, which is the STALE one. The overwrite is
correctness, not housekeeping.
Collisions are not hypothetical, they are the normal case, and they are handled by
the linear scan rather than by any probing:
  put 1 and put 1010      1010 % 1009 = 1, so both land in bucket 1
  bucket 1 = [[1, 'a'], [1010, 'b']]
  get(1) = 'a'   get(1010) = 'b'
That is also why the stored element is a (key, value) pair and not just a value.
Without the key alongside it, nothing in a shared bucket could tell the two
entries apart.
Returning -1 for a missing key is only safe because this problem says values are
non-negative. In a real map you would return an absent-marker instead, since -1
is otherwise a legitimate value.

Complexity

  • Time — O(1) average: each operation touches one bucket; with a good load factor buckets stay short.
  • Space — O(n): stored key/value pairs plus the bucket array.

Common Pitfalls

  • get must return -1 for missing keys, not 0.
  • put must overwrite an existing key rather than adding a duplicate.

Full Solution — all languages

class MyHashMap:
    def __init__(self):
        self.n = 1009
        self.buckets = [[] for _ in range(self.n)]
    def put(self, key, value):
        b = self.buckets[key % self.n]
        for p in b:
            if p[0] == key:
                p[1] = value
                return
        b.append([key, value])
    def get(self, key):
        for p in self.buckets[key % self.n]:
            if p[0] == key:
                return p[1]
        return -1
    def remove(self, key):
        b = self.buckets[key % self.n]
        for i in range(len(b)):
            if b[i][0] == key:
                b.pop(i)
                return
SensAI
Beta
Tap the mic to stop voice mode