FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

12 Hashmap (Hash Table) Interview Questions For Coding Interview

The other day, someone asked me if I were stranded on a desert island and could take only one data structure with me, what would I choose? Without a second thought, I said Hash Tables. Follow along and check 12 most common Hastmap and Hash Tables interview questions and answers for your next coding interview.

Q1: 
What is Hash Table?

Answer

A hash table (hash map) is a data structure that implements an associative array abstract data type, a structure that can map keys to values. Hash tables implement an associative array, which is indexed by arbitrary objects (keys). A hash table uses a hash function to compute an index, also called a hash value, into an array of buckets or slots, from which the desired value can be found.


Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions

Q2: 
Define what is a Hash Function?

Answer

A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes. The values are used to index a fixed-size table called a hash table. Use of a hash function to index a hash table is called hashing or scatter storage addressing.

Mathematically speaking, a hash function is usually defined as a mapping from the universe of elements you want to store in the hash table to the range {0, 1, 2, .., numBuckets - 1}.

Some properties of Hash Functions are:

  • Very fast to compute (nearly constant)
  • One way; can not be reversed
  • Output does not reveal information on input
  • Hard to find collisions (different data with same hash)
  • Implementation is based on parity-preserving bit operations (XOR and ADD), multiply, or divide.

Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions

Q3: 
Detect if a List is Cyclic using Hash Table

Answer

To detect if a list is cyclic, we can check whether a node had been visited before. A natural way is to use a hash table.

Algorithm

We go through each node one by one and record each node's reference (or memory address) in a hash table. If the current node is null, we have reached the end of the list and it must not be cyclic. If current node’s reference is in the hash table, then return true.

Complexity Analysis
Time:
Constant
O(1)
Dbl. Logarithmic
O(log log n)
Logarithmic
O(log n)
Square Root
O(√n)
Linear
O(n)
Linearithmic
O(n log n)
Quadratic
O(n2)
Exponential
O(2n)
Factorial
O(n!)
Space:
Constant
O(1)
Dbl. Logarithmic
O(log log n)
Logarithmic
O(log n)
Square Root
O(√n)
Linear
O(n)
Linearithmic
O(n log n)
Quadratic
O(n2)
Exponential
O(2n)
Factorial
O(n!)

Time: O(n)

Space: O(n)

  • Time complexity : O(n) . We visit each of the n elements in the list at most once. Adding a node to the hash table costs only O(1) time.
  • Space complexity: O(n) . The space depends on the number of elements added to the hash table, which contains at most n elements.
Implementation
public boolean hasCycle(ListNode head) {
    Set<ListNode> nodesSeen = new HashSet<>();
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}

Having Tech or Coding Interview? Check 👉 43 Linked Lists Interview Questions
Source: leetcode.com

Q4: 
What is Hashing?

Answer

Hashing is the practice of using an algorithm (or hash function) to map data of any size to a fixed length. This is called a hash value (or sometimes hash code or hash sums or even a hash digest if you’re feeling fancy). In hashing, keys are converted into hash values or indexes by using hash functions. Hashing is a one-way function.


Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions

Q5: 
What is the space complexity of a Hash Table?

Answer

The space complexity of a datastructure indicates how much space it occupies in relation to the amount of elements it holds. For example a space complexity of O(1) would mean that the datastructure alway consumes constant space no matter how many elements you put in there. O(n) would mean that the space consumption grows linearly with the amount of elements in it.

A hashtable typically has a space complexity of O(n).


Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions

Q6: 
Explain in simple terms how Hash Tables are implemented?

Answer

Hash tables are often implemented as arrays of linked lists. If we imagine a table storing people's names, after a few insertions it might be laid out in memory as below, where (enclosed numbers), like (42) are hash values of the name.

bucket#  bucket content / linked list

[0]      --> "sue"(780) --> null
[1]      null
[2]      --> "fred"(42) --> "bill"(9282) --> "jane"(42) --> null
[3]      --> "mary"(73) --> null
[4]      null
[5]      --> "masayuki"(75) --> "sarwar"(105) --> null
[6]      --> "margaret"(2626) --> null
[7]      null
[8]      --> "bob"(308) --> null
[9]      null

A few points:

  • each of the array entries (indices [0], [1]...) is known as a bucket, and starts a - possibly empty - linked list of values (aka elements, in this example - people's names)
  • each value (e.g. "fred" with hash 42) is linked from bucket [hash % number_of_buckets] e.g. 42 % 10 == [2]; % is the modulo operator - the remainder when divided by the number of buckets
  • multiple data values may collide at and be linked from the same bucket, most often because their hash values collide after the modulo operation (e.g. 42 % 10 == [2], and 9282 % 10 == [2]), but occasionally because the hash values are the same (e.g. "fred" and "jane" both shown with hash 42 above)

    • most hash tables handle collisions - with slightly reduced performance but no functional confusion - by comparing the full value (here text) of a value being sought or inserted to each value already in the linked list at the hashed-to bucket
  • If the table size grows, hash tables implemented as above tend to resize themselves (i.e. create a bigger array of buckets, create new/updated linked lists there-from, delete the old array) to keep the ratio of values to buckets (aka load factor) somewhere in the 0.5 to 1.0 range.

  • The buckets don't necessarily have to be lists or arrays, they can be any container type, such as a balanced BST. That means O(log n) worst case for collisions. But this is why it's important to choose a good hashing function to avoid putting too many elements into one bucket.

Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions

Q7: 
What is Hash Collision?

Answer

There’s always a chance that two different inputs for hash function will generate the same hash value. This is known as a hash collision. If a collision happens, you just compare the actual objects you are hashing to see if they match. What is the probability of a hash collision? This question is just a general form of the birthday problem from mathematics:

Given k randomly generated values, where each value is a non-negative integer less than N, what is the probability that at least two of them are equal?

Take the well-known hash function CRC32, for example. If you feed this function the two strings “plumless” and “buckeroo”, it generates the same value. This is known as a hash collision.


Assuming your hash values are 32-bit, 64-bit or 160-bit, the following table contains a range of small probabilities:


Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions
Source: preshing.com

Q8: 
What is complexity of Hash Table?

Answer

Hash tables are O(1) average and amortized time complexity case complexity, however it suffers from O(n) worst case time complexity (when you have only one bucket in the hash table, then the search complexity is O(n)). A hashtable typically has a space complexity of O(n).

Hash tables suffer from O(n) worst time complexity due to two reasons:

  1. If too many elements were hashed into the same key: looking inside this key may take O(n) time (for linked lists)
  2. Once a hash table has passed its load balance - it has to rehash (create a new bigger table, and re-insert each element to the table).

However, it is said to be O(1) average and amortized case because:

  1. It is very rare that many items will be hashed to the same key if you chose a good hash function and you don't have too big load balance.
  2. The rehash operation, which is O(n), can at most happen after n/2 ops, which are all assumed O(1): Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)

Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
What is the significance of load factor of a Hash Table?

Answer

Any Hash Table has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.

If the table size grows, hash tables tend to resize themselves (i.e. create a bigger array of buckets, create new/updated linked lists there-from, delete the old array) to keep the ratio of values to buckets (aka load factor) somewhere in the 0.5 to 1.0 range. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.

As a general rule, the default load factor (.75) (used in Java HashMap) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost.


Having Tech or Coding Interview? Check 👉 31 Hash Tables Interview Questions

Q10: 
Explain some technics to handle collision in Hash Tables

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q11: 
How To Choose Between a Hash Table and a Trie (Prefix Tree)?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q12: 
Compare lookup operation in Trie vs Hash Table

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...