
Problem
Solution
Submissions
Hash Map Without Using Built-in Hash Table Libraries
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a Python program to design a hash map without using any built-in hash table libraries. Implement the MyHashMap class with put, get, and remove operations.
Example 1
- Input: ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
- Output: [null, null, null, 1, -1, null, 1, null, -1]
- Explanation:
- Step 1: MyHashMap hashMap = new MyHashMap() - Initialize an empty hash map.
- Step 2: hashMap.put(1, 1) - Insert key-value pair (1, 1). Map becomes [[1,1]].
- Step 3: hashMap.put(2, 2) - Insert key-value pair (2, 2). Map becomes [[1,1], [2,2]].
- Step 4: hashMap.get(1) - Return value for key 1, which is 1.
- Step 5: hashMap.get(3) - Key 3 doesn't exist, so return -1.
- Step 6: hashMap.put(2, 1) - Update value for key 2 to 1. Map becomes [[1,1], [2,1]].
- Step 7: hashMap.get(2) - Return value for key 2, which is now 1.
- Step 8: hashMap.remove(2) - Remove key-value pair with key 2. Map becomes [[1,1]].
- Step 9: hashMap.get(2) - Key 2 no longer exists, so return -1.
Example 2
- Input: ["MyHashMap", "put", "put", "put", "get", "remove", "get"] [[], [10, 20], [30, 40], [10, 50], [10], [30], [30]]
- Output: [null, null, null, null, 50, null, -1]
- Explanation:
- Step 1: MyHashMap hashMap = new MyHashMap() - Initialize an empty hash map.
- Step 2: hashMap.put(10, 20) - Insert key-value pair (10, 20). Map becomes [[10,20]].
- Step 3: hashMap.put(30, 40) - Insert key-value pair (30, 40). Map becomes [[10,20], [30,40]].
- Step 4: hashMap.put(10, 50) - Update value for key 10 to 50. Map becomes [[10,50], [30,40]].
- Step 5: hashMap.get(10) - Return value for key 10, which is 50.
- Step 6: hashMap.remove(30) - Remove key-value pair with key 30. Map becomes [[10,50]].
- Step 7: hashMap.get(30) - Key 30 no longer exists, so return -1.
Constraints
- 0 ≤ key, value ≤ 10^6
- At most 10^4 calls will be made to put, get, and remove.
- Time Complexity: O(1) average for each operation
- Space Complexity: O(n) where n is the number of key-value pairs
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use an array of linked lists to handle collisions (chaining method).
- Consider a simple hash function like key % array_size.
- When handling collisions, search through the linked list to find the matching key.
- For better performance, choose a prime number for the array size.
- Consider resizing the array when the load factor exceeds a threshold.