
Problem
Solution
Submissions
HashMap using Array
Certification: Basic Level
Accuracy: 100%
Submissions: 2
Points: 8
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:
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1); // The map is now [[1,1]]
hashMap.put(2, 2); // The map is now [[1,1], [2,2]]
hashMap.get(1); // return 1
hashMap.get(3); // return -1 (not found)
hashMap.put(2, 1); // The map is now [[1,1], [2,1]] (update the existing value)
hashMap.get(2); // return 1
hashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
hashMap.get(2); // return -1 (not found)
Example 2
- Input:
["MyHashMap", "put", "get", "put", "put", "get", "remove", "get", "containsKey"]
[[], [10, 20], [10], [10, 30], [20, 40], [10], [20], [20], [10]] - Output: [null, null, 20, null, null, 30, null, -1, true]
- Explanation: Various operations are performed on the hash map, and the final containsKey check returns true.
Constraints
- 0 ≤ key, value ≤ 10^6
- At most 10^4 calls will be made to put, get, remove, and containsKey
- Time Complexity: O(1) average case for all operations
- Space Complexity: O(n) where n is the capacity of the hash map
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 or an array of array lists to implement the hash map
- Each entry in the hash map should store both key and value
- Implement a hash function to map keys to array indices
- Handle collisions using a technique like chaining or open addressing
- For updating a value, check if the key already exists