Tutorialspoint
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
ArraysHash MapHCL TechnologiesKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a static inner class Entry to store key-value pairs.
 Step 2: Create an array of ArrayList to handle collisions using chaining.
 Step 3: Implement a hash function that maps a key to an index in the array.
 Step 4: For put operation, check if the key already exists. If it does, update the value; otherwise, add a new entry.
 Step 5: For get operation, find the key in the appropriate bucket and return its value, or -1 if not found.
 Step 6: For remove operation, find the entry in the appropriate bucket and remove it.
 Step 7: Implement containsKey by checking if get returns a value other than -1.

Submitted Code :