Design a hash map without using any built-in hash table libraries. Implement the MyHashMap class with three methods: put(key, value) inserts or updates a key-value pair, get(key) returns the value or -1 if not found, and remove(key) deletes the key if it exists.
A hash map is a fundamental data structure that maps keys to values using a hash function. The core idea is to use an array of buckets where each bucket stores entries that share the same hash index. The hash function key % capacity determines which bucket a key belongs to. Collisions (multiple keys mapping to the same bucket) are handled with chaining — each bucket is a linked list or dynamic array of entries.
This implementation uses an array of lists with an initial capacity of 1000. Each bucket stores a list of [key, value] pairs. For put, compute the hash index, scan the bucket for the key, and either update or append. For get, compute the hash index and scan for the key. For remove, compute the hash index, find the key in the bucket, and delete the entry.
Edge cases include putting a key that already exists (overwrite), getting a key that was never inserted (return -1), removing a key that does not exist (do nothing), and handling negative keys (use absolute value in the hash function).
Example Input & Output
Key 0 is stored correctly.
Standard sequence of operations.
Negative keys work via abs hash.
Keys that may collide in same bucket.
Getting non-existent key returns -1.
Algorithm Flow

Solution Approach
Use an array of buckets. Hash function: abs(key) % capacity. Each bucket stores key-value pairs. Handle collisions via chaining with lists.
Time O(n/k) average per operation, Space O(n).
Best Answers
import java.util.*;
class MyHashMap {
private int cap = 1000;
private List<int[]>[] buckets;
public MyHashMap() {
buckets = new List[cap];
for (int i = 0; i < cap; i++) buckets[i] = new ArrayList<>();
}
private int hash(int key) { return Math.abs(key) % cap; }
public void put(int key, int value) {
int h = hash(key);
for (int[] e : buckets[h]) {
if (e[0] == key) { e[1] = value; return; }
}
buckets[h].add(new int[]{key, value});
}
public int get(int key) {
int h = hash(key);
for (int[] e : buckets[h]) {
if (e[0] == key) return e[1];
}
return -1;
}
public void remove(int key) {
int h = hash(key);
var it = buckets[h].iterator();
while (it.hasNext()) {
if (it.next()[0] == key) { it.remove(); return; }
}
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
