Top HashMap Interview Questions (10+ Short Sample Answers)

HashMap Interview Questions (At Least 10 With Short Sample Answers)

Can you imagine the awkward silence that would come in a coding interview when asked about an essential data structure called HashMap, just because everything sounds Greek to you? It is highly likely that computer science students often underestimate this important data structure because despite being used heavily in various domains, structures like arrays still overrule other data structures in aspects of popularity and learning convenience. But interviews are based on a common rule: expect the unexpected. HashMap, a structure that stores <key, Value> pairs and helps solve huge problems, is often asked about in coding interviews. Following are the 10 most commonly asked HashMap Interview Questions.

Top HashMap Interview Questions

 Question 1: Explain the internal working of HashMap.

Difficulty Level: Medium

Note before answering: Whether Hash Maps or any other data structure, whenever asked about the internal functioning or mechanics, one can answer for about 2-3 minutes, hovering over a few details and ending up giving a mere overview or a rough idea about Hash Maps. It’s important to know that, whenever asked about the internal mechanism, you should lay down every bit of a detail that matters to convince the interviewer that you are aware of behind-the-scenes of Hash Maps or any other data structure.

Answer:

1. (Start by Describing Hash Maps): HashMap is a data structure that enables us to store data in <Key, Value> pairs. A <key, Value> data pair is stored in a node. HashMap internally contains an array of nodes called a bucket. Each node in a bucket is associated with a linked list or an array to store other nodes. Other than the <Key, Value> pair, the node also contains a reference to the successor node and a hash value corresponding to the key.

2. (Start Explaining the Details): HashMap’s functioning is based on a technique that converts an object into a finger-print synonymous with a unique integer value. The technique is called hashing. hashCode() method is used to generate the unique value, known as a hash value. To insert the <key, Value> pair, we use the put() method. put() method calls the hashCode() method to calculate the hash value. Using the hash value, an index value is calculated with the help of the following formula:

Index = hash value & (n-1),

Where n=16 (default HashMap bucket size) and & denotes logical AND. Finally, the node with the specified key, value, calculated hash, and a null reference for storing the next node will be stored at the index value. In conclusion, HashMap stores buckets that store node of <key, value> pairs, which further links to successive nodes.

Question 2: What is the time complexity of basic operations get() and put() methods in the HashMap class?

Difficulty Level: Easy

Answer: The time complexity of get() and put() methods in HashMap is O(1), which means constant time. When under execution, it is so because either method calls the hashcode() method to calculate the hash value, and further, the index value is calculated. Once the index value is retrieved, the get() method returns the value corresponding to the specified key, and the put() method puts the <key, Value> pair in the HashMap. Throughout the process, a lookup procedure follows, demanding no iteration, and hence the time complexity turns out to be O(1).

Question 3: Are capacity of a HashMap and size of a HashMap same?

Difficulty Level: Easy

Answer: No, the capacity and size of a HashMap are not the same. Capacity denotes the amount of <key, Value> pairs a HashMap can store. The default initial capacity of a HashMap is 16. The size of a HashMap, on the other hand, denotes the current amount of elements being stored in the HashMap. 

Note: Capacity and size are often used in a similar sense, leading to confusion while answering such kinds of questions. So, it’s important to stay aware of the terms capacity and size, which usually differs in the programming paradigm.

Question 4: In what order are the <key, Value> pairs stored in a HashMap?

Difficulty Level: Medium

Answer: HashMap is an unordered, unsorted data structure. It stores and maintains <key, value> pairs. There is no definite order in which the <key, value> pairs are stored in a HashMap. Every iteration would result in a new, random ordering of the mappings. 

Question 5: Is HashMap thread-safe in java?

Difficulty Level: Medium-Hard

Note before answering: Answering this question requires the knowledge of multithreading and thread-safety. Multithreading enables multiple threads to run concurrently. Consequently, it leads to multiple threads accessing the same resources frequently. A code will be considered thread-safe if the code behaves similarly, without throwing any obnoxious behavior, when multiple threads are executing concurrently. 

Answer: HashMap is not thread-safe. Attempting to let multiple threads access the same HashMap won’t lead the hashmap to show a consistent behavior. This is because the hashmap is not synchronized, which means that if one thread attempts to insert a map into a hashmap, and concurrently, another thread attempts to do the same, an exception might be thrown, or you might see some unexpected behavior. 

Question 6: Explain how collisions are handled by HashMap in java?

(Alternative) When does a collision occur in hash function and how does a hashmap handle it?

Difficulty Level: Hard

Answer: When a hash function ends up returning the same bucket for two distinct keys, a collision is said to occur. A hashmap uses a hash function to compute the hash value and uses it to compute the bucket. There is a possibility that two unique keys lead to the computation of the same bucket. This occurs because two distinct keys have the same hashcode. HashMap handles collision by employing a linked list, such that multiple keys hashing to the same bucket will keep on appending in the linked list. However, after version 8, the linked list has been replaced with a balanced tree to improve its performance. In a situation when all the keys happen to have the same hashcode, then technically, the hashmap no longer remains a hashmap and becomes a linked list. However, a read-only hashmap can still be used in a multi-threading environment.

Question 7: Is it possible to store a duplicate key in a HashMap?

Difficulty Level: Easy

Answer: – In a HashMap, many to one relation is feasible but not one to many. So, it’s not possible to store duplicate keys in a hashmap. Multiple keys can map to the same value, but a single key cannot be duplicated or imitated to store distinct values. Trying to store a duplicate key would simply replace the old value of the key with the current value. As a result, the hashmap’s size will not change because there has been no addition of duplicate keys.

Question 8: How are null keys handled in a HashMap?

Difficulty Level: Medium

Answer: Null keys are handled, especially in HashMap. Whenever we insert a key, HashMap calls the hashCode() method to store the mapping. But when we insert null as a key, HashMap doesn’t call the hashCode() method. The default initial bucket size is 16, and HashMap places the null key in the 0th bucket, storing the value passed as the null key’s corresponding value. The data structure that HashMap uses internally to implement this is a linked list. During the get() method call, the lookup procedure searches for the null key in the 0th bucket. Another important thing to remember is that a hashmap object can’t store multiple null keys. There can only be one null key in a hashmap. 

Question 9: Imagine not keeping a record of keys that you’ve added in the hashmap and the next key you try to insert is already present in the hashmap. How will the HashMap respond?

Difficulty Level: Easy-Medium

Answer: HashMaps are pretty smart in not throwing an error when you attempt to add a key already present in the hashmap. The compiler will not throw an error as one might expect. Rather, the value linked with the key we are trying to insert will be looked at and replaced with the current value. For instance, if you try to insert a key, say red and a value, say 2, using the put() function and the key red already exist in the hashmap, then the previous value of the key red will be replaced with the current value, i.e., 2. Consequently, there will be no change in the size of the hashmap.

Question 10: Is hashmap implemented as a data structure on its own? 

Difficulty Level: Medium

Answer: No. HashMap is not implemented directly on its own. It’s a combination of the 2 most commonly used fundamental data structures in java, arrays, and linked list. Linked List serves as a storage place for <key, Value> pairs, and arrays are used to store the linked lists into those. To improve performance, a linked list can be replaced with a binary search tree from Java 8.

Also read Top 15 Video Interview Questions [Sample Answers]

Top HashMap Interview Questions (10+ Short Sample Answers)

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top