Implement HashMap Internals

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-01

Problem Statement

Design and implement a simplified HashMap data structure from scratch, focusing on internal mechanics such as hashing, collision handling, resizing, and thread-safety considerations.


Functional Requirements


1.<span></span>Core APIs
2.<span></span>put(K key, V value) → Insert or update a key-value pair.
3.<span></span>get(K key) → Retrieve value for the given key (return null/exception if not found).
4.<span></span>remove(K key) → Remove the mapping for the given key.
5.<span></span>containsKey(K key) → Check if a key exists.
6.<span></span>size() → Return the number of key-value pairs.
7.<span></span>Internal Mechanics
8.<span></span>Use hashing to compute bucket index from key.
9.<span></span>Handle collisions (either via chaining (linked list / tree) or open addressing).
10.<span></span>Maintain load factor threshold → when exceeded, resize and rehash.
11.<span></span>Performance Constraints
12.<span></span>Average case O(1) for put, get, remove.
13.<span></span>Worst case O(n) in case of hash collisions.
14.<span></span>Space efficient — avoid unnecessary memory growth.
15.<span></span>Concurrency (Extension)
16.<span></span>Ensure thread-safety if accessed by multiple threads (design discussion: locks vs lock-free).
17.<span></span>Compare non-thread-safe HashMap vs ConcurrentHashMap approaches.


Non-Functional Requirements


1.<span></span>Should handle null keys (decide if allowed, like Java HashMap allows one).
2.<span></span>Should allow null values.
3.<span></span>Must preserve no ordering (not like LinkedHashMap).
4.<span></span>Ensure correctness during resize + rehashing under load.


Example Usage


<div><div>java</div><div>CopyEdit</div><div>MyHashMap<Integer, String> map = new MyHashMap<>();</div><div>map.put(1, "Alice");</div><div>map.put(2, "Bob");</div><div><br /></div><div>System.out.println(map.get(1)); // "Alice"</div><div>System.out.println(map.containsKey(3)); // false</div><div><br /></div><div>map.remove(2);</div><div>System.out.println(map.size()); // 1</div></div>


Deliverables


1.<span></span>Class Design: Node<K,V>, Bucket, MyHashMap<K,V>.
2.<span></span>Hash function design & collision handling strategy.
3.<span></span>Implementation of put, get, remove, resize.
4.<span></span>Stress test with large input dataset.


Solution

Comments