Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access to data becomes very fast if we know the index of the desired data.
Thus, it becomes a data structure in which insertion and search operations are very fast irrespective of the size of the data. Hash Table uses an array as a storage medium and uses the hash technique to generate an index where an element is to be inserted or is to be located from.
Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use modulo operator to get a range of key values. Consider an example of a hash table of size 20, and the following items are to be stored. Item is in the (key, value) format.
Here we have a hash function that takes in keys and generates indices for a table. These indices let us know where the value is stored. Now whenever we want to search for a value associated with a key, we just need to run the hash function on the key again and get the value in nearly constant time.
Hash functions are pretty hard to design though. Let's take an example −
Let's say we have the following hash function −
function modBy11(key) { return key % 11; }
And we start running this on key-value pairs we want to store, for example −
Here we see that we have a collision, ie, if we were to store 15 first and then encounter the key 26 with this hash function, it'll try to fix this entry in the same hole. This is called a collision. And to handle such situations, we need to define a collision handling mechanism. There are some well defined simple collision resolution algorithms. For example −
Now that we understand how a hash table works and how we can use collision resolution, let's implement the HashTable class.
We'll implement these methods in our implementation −