817. Design HashMap
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a MyHashMap class from scratch, without using any built-in hash table libraries. We need to implement three core functionalities: put(key, value) to insert or update a key-value pair, get(key) to retrieve a value by its key, and remove(key) to delete a key-value pair.
Solution
Design HashMap in Python
class MyHashMap:
def __init__(self):
# Using a prime number for capacity helps in distributing keys more uniformly.
self.capacity = 1009
# Initialize buckets as a list of empty lists.
# Each sublist will store [key, value] pairs for a given hash index.
self.buckets = [[] for _ in range(self.capacity)]
def _hash(self, key: int) -> int:
# Simple hash function to map a key to a bucket index.
return key % self.capacity
def put(self, key: int, value: int) -> None:
index = self._hash(key)
chain = self.buckets[index]
# Search for the key in the chain.
for i, (k, v) in enumerate(chain):
if k == key:
# Key found, update the value.
chain[i][1] = value
return
# Key not found, add a new [key, value] pair.
chain.append([key, value])
def get(self, key: int) -> int:
index = self._hash(key)
chain = self.buckets[index]
# Search for the key in the chain.
for k, v in chain:
if k == key:
# Key found, return the value.
return v
# Key not found.
return -1
def remove(self, key: int) -> None:
index = self._hash(key)
chain = self.buckets[index]
# Search for the key and remove it.
for i, (k, v) in enumerate(chain):
if k == key:
# Remove the pair by index using pop.
chain.pop(i)
return
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
Design HashMap in Java
class MyHashMap {
// A simple container for key-value pairs to store in the chains.
class Pair {
int key;
int value;
public Pair(int key, int value) {
this.key = key;
this.value = value;
}
}
private final int capacity = 1009; // A prime number for capacity.
private LinkedList<Pair>[] buckets; // Array of linked lists for separate chaining.
// Hash function to map a key to a bucket index.
private int hash(int key) {
return key % capacity;
}
public MyHashMap() {
buckets = new LinkedList[capacity];
for (int i = 0; i < capacity; i++) {
buckets[i] = new LinkedList<Pair>();
}
}
public void put(int key, int value) {
int index = hash(key);
LinkedList<Pair> chain = buckets[index];
// Search for the key in the chain.
for (Pair pair : chain) {
if (pair.key == key) {
// Key exists, update its value.
pair.value = value;
return;
}
}
// Key doesn't exist, add a new pair to the chain.
chain.add(new Pair(key, value));
}
public int get(int key) {
int index = hash(key);
LinkedList<Pair> chain = buckets[index];
// Search for the key in the chain.
for (Pair pair : chain) {
if (pair.key == key) {
// Key found, return its value.
return pair.value;
}
}
// Key not found.
return -1;
}
public void remove(int key) {
int index = hash(key);
LinkedList<Pair> chain = buckets[index];
// Using an iterator is the efficient and safe way to remove elements
// from a collection while iterating over it.
Iterator<Pair> iterator = chain.iterator();
while (iterator.hasNext()) {
Pair pair = iterator.next();
if (pair.key == key) {
iterator.remove();
return; // Key found and removed.
}
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/
Design HashMap in C++
class MyHashMap {
private:
// A prime number is often chosen for capacity to help with uniform distribution.
const int capacity = 1009;
std::vector<std::list<std::pair<int, int>>> buckets;
// Hash function to map key to a bucket index.
int hash(int key) {
return key % capacity;
}
public:
MyHashMap() {
buckets.resize(capacity);
}
void put(int key, int value) {
int index = hash(key);
// Find the list corresponding to the key's hash.
auto& chain = buckets[index];
// Iterate through the list to find if the key already exists.
for (auto& entry : chain) {
if (entry.first == key) {
// Key found, update the value and return.
entry.second = value;
return;
}
}
// Key not found, add a new key-value pair to the list.
chain.push_back({key, value});
}
int get(int key) {
int index = hash(key);
// Find the list corresponding to the key's hash.
const auto& chain = buckets[index];
// Iterate through the list to find the key.
for (const auto& entry : chain) {
if (entry.first == key) {
// Key found, return its value.
return entry.second;
}
}
// Key not found.
return -1;
}
void remove(int key) {
int index = hash(key);
// Find the list corresponding to the key's hash.
auto& chain = buckets[index];
// Use remove_if to find and remove the element with the matching key.
// This is a concise way to erase an element from a std::list based on a condition.
chain.remove_if([key](const std::pair<int, int>& entry) {
return entry.first == key;
});
}
};
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap* obj = new MyHashMap();
* obj->put(key,value);
* int param_2 = obj->get(key);
* obj->remove(key);
*/
Design HashMap in TypeScript
class MyHashMap {
private capacity: number;
// Each bucket is an array of [key, value] tuples.
private buckets: Array<Array<[number, number]>>;
constructor() {
// Using a prime number for capacity helps in distributing keys more uniformly.
this.capacity = 1009;
// Initialize buckets as an array of empty arrays.
this.buckets = new Array(this.capacity).fill(null).map(() => []);
}
private hash(key: number): number {
return key % this.capacity;
}
put(key: number, value: number): void {
const index = this.hash(key);
const chain = this.buckets[index];
// Search for the key in the chain.
for (let i = 0; i < chain.length; i++) {
if (chain[i][0] === key) {
// Key found, update the value.
chain[i][1] = value;
return;
}
}
// Key not found, add a new [key, value] pair.
chain.push([key, value]);
}
get(key: number): number {
const index = this.hash(key);
const chain = this.buckets[index];
// Search for the key in the chain.
for (const [k, v] of chain) {
if (k === key) {
// Key found, return the value.
return v;
}
}
// Key not found.
return -1;
}
remove(key: number): void {
const index = this.hash(key);
const chain = this.buckets[index];
// Find the index of the pair to remove.
for (let i = 0; i < chain.length; i++) {
if (chain[i][0] === key) {
// Remove the pair using splice.
chain.splice(i, 1);
return;
}
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* var obj = new MyHashMap()
* obj.put(key,value)
* var param_2 = obj.get(key)
* obj.remove(key)
*/
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.