Internal implementation of HashMap

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-12-11

Problem Statement

Design and implement a HashMap data structure from scratch. The focus is on object-oriented design, modularity, and understanding internal mechanisms such as hashing, collision resolution, and resizing.


✅ Functional Requirements


1.Core Operations
•put(K key, V value) → Insert or update a key-value pair.
•get(K key) → Retrieve the value for a key.
•remove(K key) → Remove a key-value pair.
•containsKey(K key) → Check if a key exists.
•size() → Return number of key-value pairs.
2.Internal Mechanics
•Use a hash function to map keys to bucket indices.
•Handle collisions using:
•Chaining (linked list or tree per bucket)
•Open addressing (linear probing, quadratic probing, or double hashing)
3.Dynamic Resizing
•Automatically resize the internal array when load factor threshold is exceeded.
•Rehash keys after resizing to maintain performance.
4.Optional Features
•Support for custom hash functions.
•Iterators to traverse key-value pairs.
•Thread-safety (optional, otherwise single-threaded).


🔐 Constraints & Assumptions


•Language: C++ / Java.
•Focus is on LLD, not using built-in HashMap/Dictionary.
•Assume keys implement hashCode() / equals() or equivalent.
•Target average O(1) time complexity for get and put.


🧱 Key Components & Classes


1.HashMap Class
1 2template <typename K, typename V> 3class HashMap { 4private: 5 vector<Bucket*> buckets; 6 int bucketCount; 7 float loadFactor; 8 int size; 9 void resize(); 10 int getBucketIndex(K key); 11public: 12 void put(K key, V value); 13 V get(K key); 14 void remove(K key); 15 bool containsKey(K key); 16 int size(); 17};
1.Bucket Class
1 2template <typename K, typename V> 3class Bucket { 4private: 5 list<pair<K,V>> entries; // or tree for optimized lookups 6public: 7 void put(K key, V value); 8 V get(K key); 9 void remove(K key); 10 bool containsKey(K key); 11};
1.Hash Function / Utility
•Computes hashCode for a key and maps it to a bucket index.


🔄 Example Workflow


1.put("Alice", 25) → compute hash → bucket index 3 → insert into bucket → check load factor → resize if necessary.
2.get("Alice") → compute hash → bucket index 3 → search in bucket → return value.
3.remove("Alice") → compute hash → bucket index 3 → remove entry from bucket.
4.Resize occurs when size / bucketCount > loadFactor → double buckets → rehash entries.


🧪 Expected Deliverables


•Class diagram showing HashMap, Bucket, and relationships.
•Implementation of core operations: put, get, remove, containsKey.
•Test cases:
•Insert, update, remove, and retrieve keys
•Collision handling scenarios
•Automatic resizing and rehashing


💡 Discussion Points


•Trade-offs: chaining vs open addressing.
•Load factor selection for performance vs memory trade-offs.
•Resizing cost and amortized analysis.
•Extensibility: support for thread-safety or concurrent access


Solution

Comments