Implement hashmap functions
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-06-30
Problem Statement
Design and implement a HashMap (key-value store) from scratch that supports basic operations like insertion, retrieval, and deletion with efficient average-case performance. Focus on hashing, collision handling, and dynamic resizing.
Functional Requirements (FR)
Core Operations
•put(key, value) → Insert or update a key-value pair.
•get(key) → Retrieve the value associated with a key. Returns null or -1 if key is not present.
•remove(key) → Delete a key-value pair if it exists.
Additional Operations (Optional)
•containsKey(key) → Check if a key exists.
•size() → Returns the number of elements in the map.
•keys() → Returns a list of all keys.
•values() → Returns a list of all values.
Non-Functional Requirements (NFR)
•Performance → O(1) average-case for get and put.
•Memory Efficiency → Minimal memory overhead for hash table and linked structures.
•Scalability → Handle large number of key-value pairs.
•Consistency → Correct behavior during collisions and resizing.
Core Entities & Attributes
HashMap<K, V>
•capacity → Total number of buckets in the hash table.
•size → Current number of elements.
•buckets[] → Array of bucket lists (for separate chaining).
•loadFactor → Threshold to trigger resizing.
Node / Entry<K, V>
•key → Key of the entry.
•value → Value of the entry.
•next → Pointer to the next node in case of collision (linked list).
Core Components
Hash Function
•Converts a key into a bucket index.
•Should minimize collisions.
Bucket / Linked List
•Handles collisions using separate chaining.
•Stores multiple nodes with the same hash index.
Resizing Mechanism
•Dynamically increase capacity when load factor exceeds threshold.
•Rehash existing entries into new buckets.
HashMap Class
•Implements all core operations (put, get, remove).
•Manages collision handling and resizing.
APIs / Operations
Core APIs
•put(key: K, value: V): void
•get(key: K): V
•remove(key: K): void
Optional APIs
•containsKey(key: K): boolean
•size(): int
•keys(): List<K>
•values(): List<V>
LLD Design Goals
•Class Diagram → HashMap<K,V> containing array of Bucket / Entry<K,V>.
Design Patterns:
•Composite / Linked List → For handling collisions in a bucket.
•Factory (Optional) → For creating entries.
•Concurrency Handling (Optional) → Use locks for thread-safe access.
•Trade-offs →1. Separate chaining uses extra memory but handles collisions well.2. Open addressing reduces memory overhead but can degrade performance at high load.