FrontendInterviews.dev

Loading problem…

98. Design HashMap

Easy•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

You're building a custom HashMap implementation. This is useful for understanding how hash maps work internally and for implementing custom key-value storage.

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

Implement the MyHashMap class:

  • MyHashMap() initializes the object with an empty map.
  • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists, update the value.
  • int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • void remove(int key) removes the key and its corresponding value if the map contains the mapping for the key.

Requirements

1. Basic Functionality

  • Implement put, get, and remove operations
  • Handle key collisions
  • Efficient O(1) average time complexity
  • Handle key updates

Example Usage

const map = new MyHashMap();
map.put(1, 1);
map.put(2, 2);
map.get(1);    // 1
map.get(3);    // -1
map.put(2, 1); // update
map.get(2);    // 1
map.remove(2);
map.get(2);    // -1

Real-World Context

This problem models real data structure implementation:

  • Custom HashMap: Implement hash map from scratch
  • Data structure design: Understand hash map internals
  • Collision handling: Handle hash collisions
  • Performance: O(1) average operations

Constraints

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