![]() |
VOOZH | about |
In hashing there is a hash function that maps keys to some values. But these hashing functions may lead to a collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.
For a more detailed explanation and theoretical background on this approach, please refer to Hashing | Set 2 (Separate Chaining).
Let's create a hash function, such that our hash table has 'n' number of buckets.
To insert a node into the hash table, we first compute the hash index for the given key using a hash function:
hashIndex = key % noOfBuckets.
This index determines the appropriate bucket where the node should be inserted.
Example:
noOfBuckets = 7
keys to insert = [15, 11, 27, 8]
For each key:
Insert: Move to the bucket corresponding to the above-calculated hash index and insert the new node at the end of the list.
Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponding to the calculated hash index, and search the list in the current bucket to find and remove the node with the given key (if found).
Table of Content
This method has not concept of rehashing. It only has a fixed size array i.e. fixed numbers of buckets.
0 --> 7 1 2 3 4 --> 18 --> 25 5 6
Time Complexity:
Auxiliary Space: O(1), since no extra space has been taken.
Let's discuss another method where there is no limitation on the number of buckets. The number of buckets increases when the load factor exceeds 0.5.
We will do rehashing when the value of load factor is greater than 0.5. In rehashing, we double the size of array and add all the values again to new array (doubled size array is new array) based on hash function. Hash function should also be change as it is depends on number of buckets. Therefore, hash function behaves differently from the previous one.
0 --> 15 1 2 --> 27 3 4 After rehashing: 0 --> 15 1 2 --> 27 3 4 --> 19
Complexity analysis of Insert:
Complexity analysis of Search: