Implement a custom Hash Map

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-09-18

Problem Statement

Design and implement a custom HashMap data structure that provides efficient storage and retrieval of key-value pairs using hashing techniques.

Functional Requirements (FR)


Basic Operations


•put(key, value) → Insert or update a key-value pair.
•get(key) → Retrieve value for a given key.
•remove(key) → Delete the key-value mapping.
•containsKey(key) → Check if a key exists.
•size() → Return the number of stored entries.


Collision Handling


•Support collision resolution using separate chaining (linked list/bucket) or open addressing (linear probing, quadratic probing, or double hashing).


Resizing


•Automatically resize (rehash) when load factor exceeds a threshold (e.g., 0.75).


Null Handling


•Decide whether to allow null keys and/or null values (like Java’s HashMap).


Iteration (Optional/Advanced)


•Support iterating over keys, values, and entries.


Non-Functional Requirements (NFR)


Time Complexity


•Average-case O(1) for put, get, remove.
•Worst-case O(n) in case of many collisions.


Space Efficiency


•Minimize memory overhead while maintaining performance.


Thread Safety (Optional)


•Base implementation can be non-thread-safe.
•Advanced version: support concurrent access with synchronization.


Core Classes & Entities


HashMap<K, V>


•Internal array of buckets (Node[]).
•Hash function implementation.
•Load factor and capacity management.


Node<K, V> (Entry)


•Attributes: key, value, hash, next.
•Used for separate chaining.


APIs / Methods


•public V put(K key, V value)
•public V get(K key)
•public V remove(K key)
•public boolean containsKey(K key)
•public int size()
•private void resize()


Design Decisions & Trade-offs


•Hash Function → Good distribution minimizes collisions.
•Collision Strategy → Separate chaining is easier to implement; open addressing saves space but complicates rehashing.
•Resizing Policy → Balance between performance (fewer collisions) and memory usage.
•Thread Safety → Can extend later with synchronized wrappers or concurrent hash map design.


✅ This LLD problem is a classic interview question that checks understanding of hashing, collision resolution, memory management, and system trade-offs.

Solution

Comments