We strongly recommend to refer below post as a prerequisite of this.
Hashing | Set 1 (Introduction)
What is Collision?
Since a hash function gets us a small number for a key which is a big integer or string, there is possibility that two keys result in same value. The situation where a newly inserted key maps to an already occupied slot in hash table is called collision and must be handled using some collision handling technique.
What are the chances of collisions with large table?
Collisions are very likely even if we have big table to store keys. An important observation is Birthday Paradox. With only 23 persons, the probability that two people have same birthday is 50%.
How to handle Collisions?
There are mainly two methods to handle collision:
1) Separate Chaining
2) Open Addressing
In this article, only separate chaining is discussed. We will be discussing Open addressing in next post.
The idea is to make each cell of hash table point to a linked list of records that have same hash function value.
1) Simple to implement.
2) Hash table never fills up, we can always add more elements to chain.
3) Less sensitive to the hash function or load factors.
4) It is mostly used when it is unknown how many and how frequently keys may be inserted or deleted.
1) Cache performance of chaining is not good as keys are stored using linked list. Open addressing provides better cache performance as everything is stored in same table.
2) Wastage of Space (Some Parts of hash table are never used)
3) If the chain becomes long, then search time can become O(n) in worst case.
4) Uses extra space for links.
Performance of Chaining:
Performance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of table (simple uniform hashing).
m = Number of slots in hash table n = Number of keys to be inserted in hash table Load factor α = n/m Expected time to search = O(1 + α) Expected time to insert/delete = O(1 + α) Time complexity of search insert and delete is O(1) if α is O(1)
Open Addressing for Collision Handling
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Double Hashing
- C++ program for hashing with chaining
- Index Mapping (or Trivial Hashing) with negatives allowed
- Top 20 Hashing Technique based Interview Questions
- Implementing our Own Hash Table with Separate Chaining in Java
- Given an array of pairs, find all symmetric pairs in it
- Longest Consecutive Subsequence
- Hashing | Set 3 (Open Addressing)
- Count distinct elements in every window of size k
- Find Itinerary from a given list of tickets
- Advantages of BST over Hash Table
- Hashing | Set 1 (Introduction)
- Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
- Find whether an array is subset of another array | Added Method 3
- Given an array A and a number x, check for pair in A with sum as x