Design HashMap solution explained

Design HashMap asks you to build put, get and remove for integer keys without using the language's own hash table. The standard answer is separate chaining: an array of buckets, a hash that turns a key into a bucket index, a short list of key-value pairs in each bucket, and a resize that doubles the bucket array when the table gets too full. That gives O(1) average time per operation and O(n) space.

By Published 9 min read

The task, restated

Write a class with three methods. put(key, value) stores the value for that key, replacing any older value. get(key) returns the stored value, or -1 when the key is absent. remove(key) deletes the key if it exists and does nothing otherwise. Keys and values are integers. The one rule that makes this a design question: you may use arrays and lists, but not the dictionary, Map, HashMap or set types your language already provides.

A made-up script, using 8 buckets so that keys 3 and 11 collide
CallReturnsBucket touchedNote
put(3, 30)3new key
put(11, 110)311 mod 8 is also 3, so the chain grows to two pairs
get(11)1103walk the chain until the key matches
put(3, 31)3existing key, value overwritten, size unchanged
get(3)313
remove(11)3pair removed from the chain
get(11)-13gone
remove(42)2absent key, nothing happens
A made-up script, using 8 buckets so that keys 3 and 11 collide. Scroll sideways on a small screen.

Questions worth asking first: how large can keys get, and can they be negative? Roughly how many operations will run? Is memory tight? If keys are promised to stay below a small bound, the interviewer may be happy with the array answer below, and you can skip straight to discussing what changes for arbitrary keys.

What the interviewer wants to see

This problem is rarely about the code, which is short. It tests whether you know what sits under the dictionary you use every day. Expect follow-up questions on collisions, load factor, resizing cost, and why a bad hash turns O(1) into O(n). Some interviewers run it as a conversation that starts with the naive answer and keeps raising the bar.

  • What happens when two keys land in the same bucket? Chaining keeps both in a list; open addressing probes for the next free slot.
  • When do you resize, and what does it cost? Doubling past a load factor keeps chains short; one resize is O(n), but spread over all inserts it is O(1) amortized.
  • Why not a fixed 10,000-slot array? It works until n grows past it, then every chain gets long. Fixed sizes trade memory now for speed later.
  • How would you support string keys? Compute an integer hash from the characters, for example a polynomial rolling hash, then reduce it modulo the bucket count.

Two simple starting points

The most naive design is one list of [key, value] pairs. Every operation scans the list, so each is O(n). It is correct and makes a fine opening sentence, but say right away that it is slow.

If the interviewer confirms keys are small non-negative integers, direct addressing is better: an array with one slot per possible key, holding the value or a marker for empty. Every operation is a single array access, O(1) worst case, not just on average. The catch is memory proportional to the key range rather than to the number of keys stored, which rules it out the moment keys can be huge or negative.

class ArrayMap:
    def __init__(self, max_key):
        self.cells = [-1] * (max_key + 1)

    def put(self, key, value):
        self.cells[key] = value

    def get(self, key):
        return self.cells[key]

    def remove(self, key):
        self.cells[key] = -1
Direct addressing for keys known to lie in 0 to max_key.

This version leans on values never being -1, since -1 doubles as the empty marker. If -1 is a legal value, store a separate presence flag per slot.

Optimal general design: separate chaining with resizing

Keep an array of buckets, each a small list of [key, value] pairs. To find a key, compute its bucket as key mod the number of buckets and walk that one list. Keep a count of stored pairs. When count divided by bucket count passes a threshold, often around 0.75, allocate twice as many buckets and move every pair to its new bucket. With a reasonable hash, chains stay a handful of entries long on average, so all three operations run in O(1) average time.

class MyHashMap:
    def __init__(self, buckets=8):
        self.slots = [[] for _ in range(buckets)]
        self.count = 0

    def _chain(self, key):
        return self.slots[key % len(self.slots)]

    def put(self, key, value):
        chain = self._chain(key)
        for pair in chain:
            if pair[0] == key:
                pair[1] = value
                return
        chain.append([key, value])
        self.count += 1
        if self.count > 0.75 * len(self.slots):
            self._grow()

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

    def remove(self, key):
        chain = self._chain(key)
        for i, pair in enumerate(chain):
            if pair[0] == key:
                chain[i] = chain[-1]
                chain.pop()
                self.count -= 1
                return

    def _grow(self):
        old = self.slots
        self.slots = [[] for _ in range(2 * len(old))]
        for chain in old:
            for key, value in chain:
                self._chain(key).append([key, value])
Python: lists as buckets, doubling when the load factor passes 0.75.
class MyHashMap {
  constructor(buckets = 8) {
    this.slots = Array.from({ length: buckets }, () => []);
    this.count = 0;
  }

  chain(key) {
    const m = this.slots.length;
    return this.slots[((key % m) + m) % m];
  }

  put(key, value) {
    const chain = this.chain(key);
    for (const pair of chain) {
      if (pair[0] === key) {
        pair[1] = value;
        return;
      }
    }
    chain.push([key, value]);
    this.count += 1;
    if (this.count > 0.75 * this.slots.length) this.grow();
  }

  get(key) {
    for (const [k, v] of this.chain(key)) {
      if (k === key) return v;
    }
    return -1;
  }

  remove(key) {
    const chain = this.chain(key);
    for (let i = 0; i < chain.length; i++) {
      if (chain[i][0] === key) {
        chain[i] = chain[chain.length - 1];
        chain.pop();
        this.count -= 1;
        return;
      }
    }
  }

  grow() {
    const old = this.slots;
    this.slots = Array.from({ length: old.length * 2 }, () => []);
    for (const chain of old) {
      for (const [k, v] of chain) this.chain(k).push([k, v]);
    }
  }
}
JavaScript: plain arrays only; note the double modulo for negative keys.

Two details in that code are worth pointing out unprompted. Removal swaps the found pair with the last pair and pops, which is O(1) once the pair is found and is fine because order inside a bucket does not matter. And the JavaScript remainder operator keeps the sign of the key, so -5 % 8 is -5, an invalid index; adding m and taking the remainder again maps every integer into 0 to m - 1. Python's % already returns a non-negative result for a positive divisor.

Choosing the bucket count and hash

Key mod bucket count is a fine hash for random integers, but patterned keys can defeat it. If every key is a multiple of 8 and there are 8 buckets, all keys share one bucket and every operation degrades to O(n). Two common defenses: use a prime number of buckets, or scramble the key first, for example by multiplying by a large odd constant and keeping the high bits. Mention the risk even if you keep the simple hash in code; it shows you know where the O(1) promise comes from.

The other family: open addressing

Instead of lists, store pairs directly in one array. On a collision, step to the next slot (linear probing) until you find the key or an empty slot. Lookups are cache friendly because they read neighboring cells. Removal is the tricky part: blanking a slot would cut the probe chain for keys stored after it, so you mark it with a tombstone that lookups skip over and inserts may reuse. Open addressing needs a lower load factor, often around a half to two thirds, because clusters of filled slots grow quickly. If the interviewer asks which you would pick, chaining is simpler to get right on a whiteboard; open addressing tends to be faster in practice.

Time and space

n stored pairs, U possible keys
Designput / get / removeWorst caseSpace
Single list of pairsO(n)O(n)O(n)
Direct-address arrayO(1)O(1)O(U)
Chaining, fixed bucket count bO(1 + n / b) averageO(n)O(n + b)
Chaining with doublingO(1) average, amortized for putO(n)O(n)
Open addressing with tombstonesO(1) average at a moderate loadO(n)O(capacity)
n stored pairs, U possible keys. Scroll sideways on a small screen.

Edge cases

  • Overwriting an existing key must not increase the count, or the table resizes too early.
  • Removing an absent key is a no-op, and must not decrease the count.
  • Negative keys: safe in Python, need the double modulo in JavaScript or a similar fix in C++.
  • Key 0 and value 0 are ordinary data. Watch for code that tests truthiness instead of comparing keys.
  • Removing then re-adding the same key should behave like a fresh insert.
  • Very large keys: Python integers are unbounded; in JavaScript, keys beyond 2 to the 53rd power stop being exact numbers.

Mistakes to avoid

  • Appending a new pair on put without first checking whether the key already exists, which leaves two values for one key.
  • Resizing without rehashing: copying old buckets in place keeps keys in the wrong positions for the new modulus.
  • Shrinking the count when remove finds nothing.
  • Deleting a slot outright under open addressing, which hides keys stored after it in the probe sequence.
  • Quoting O(1) without the word average. The worst case is O(n) for any design with collisions.
  • Using the language's own dict or Map inside a bucket, which the problem forbids.

How to explain it out loud

Fictional example

From naive to the real answer
Candidate
If keys are bounded and small I'd just use an array indexed by key. You said they can be any integer, so I'll do separate chaining.
Candidate
An array of buckets, the bucket is key mod the bucket count, and each bucket is a short list of pairs. Put updates in place or appends, get scans one list, remove swaps with the last pair and pops.
Candidate
When the count passes three quarters of the bucket count I double and rehash everything. That keeps chains short, so each operation is constant on average and put is amortized constant.

LFU Cache is a design question that assumes the map you just built and adds ordered buckets on top. Design Circular Queue is another fixed-array design where index arithmetic does the work, and it pairs well with this one in a design-focused study session. Two Sum is a reminder of why hash maps matter at all: it turns an O(n²) search into one pass.

Rehearsing with Natively

Natively runs on your Mac or Windows PC during practice and can read a design prompt from a screenshot, then sketch a solution with code you can check yours against. Because it transcribes the session, you can look back at how you explained load factor and resizing, which is where many candidates lose clarity. The AI interview assistant page explains how to set it up for mock rounds.

Questions people ask

How do you design a hash map without built-in libraries?

Use an array of buckets, map each key to a bucket with key mod the bucket count, and store a short list of key-value pairs in each bucket. Double the bucket array and rehash when the load factor passes about 0.75.

What is the time complexity of a hash map?

Put, get and remove are O(1) on average with a reasonable hash and load factor, and put is O(1) amortized because of resizing. The worst case is O(n) when many keys collide.

What is the difference between chaining and open addressing?

Chaining keeps colliding keys in a list per bucket. Open addressing stores every pair in the array itself and probes for the next free slot, which needs tombstones for removal and a lower load factor.

Why do negative keys need care in JavaScript?

The % operator keeps the sign of the left side, so -5 % 8 is -5. Use ((key % m) + m) % m to get a valid bucket index.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP