In universities, each student is assigned a unique roll number that can be used to retrieve information about them.
In libraries, each book is assigned a unique number that can be used to determine information about the book, such as its exact position in the library or the users it has been issued to etc.
hash functions. The values are then stored in a data structure called hash table. The idea of hashing is to distribute entries key/value pairs uniformly across an array.The basic idea of a hashtable is the ability to store the key into this data structure, and quickly retrieve the value. This is done through what we call a hash. A hash is the ability to encode the key that will eventually map to a specific location in the data structure that we can look at directly to retrieve the value.
Since we are able to hash our key and determine the exact location where our value is stored, we can do a lookup in an O(1) time complexity.
A hash function is any function that can be used to map a data set of an arbitrary size to a data set of a fixed size, which falls into the hash table. The values returned by a hash function are called hash values, hash codes, hash sums, or simply hashes.
The hash code is used again to read something from the hash map. Take the key, run it through the hash code to get a number, use that number to index the array.
A collision is what happens when more than one key gets hashed to the same location of the hashtable.
Collisions are solved by changing the initial state of the buckets. Instead of starting them all as null we can initialize a LinkedList in each one
array, it’s like the size 1024. this is important for index placement. After you have created your array of the appropriate size, do some sort of logic to turn that key into a numeric number value.Example:
Key = “Cat” Value = “Josie”
67 + 97 + 116 = 280
280 * 599 = 69648
69648 % 1024 = 16
Key gets placed in index of 16.
We now know that our
key Catmaps toindex 16of the array. We can view into this index and findJosie, our valuequickly.
key, gets the Hash, and goes to the index location specified. Once at the index location is found in the array, it is then the responsibility of the algorithm the iterate through the bucket and see if the key exists and return the value.key, and return a bool on if that key exists inside the hashtable. The best way to do this is to have the contains call the GetHash and check the hashtable if the key exists in the table given the index returned.key as a string, conduct the hash, and then return the index of the array where the key/value should be placed.References:
@By codefellows/Hashtables
@By hackerearth/Basics of Hash Tables