Hash Tables
Last updated
Was this helpful?
Last updated
Was this helpful?
Hash tables is a data structure in which every value is associated with a key and we can find that key using hash function.
β οΈ Read more about the basics of Hashing and Hash tables.
βοΈAll the code snippets you will see below are just Pseudo code.
Put
Remove
Search
Size
IsEmpty
Initial Hash table
Put Operation
Remove Operation
βοΈThe technique which I am using to find out size is very time consuming. This is one way but the better one will be to use a counter for size. Just increment that counter whenever we put an item in Hash table and decrement it when we delete an item. Just return that counter in the size function so that we do not have to iterate over whole Hash Table very time we call it ( Some geek pointed this on reddit threadβ¦ thank you) and in next post I will implement this.
Then why are you still using it here ? I am still using this because you can use this piece of code for a lot of other things i.e you can use this to traverse over whole Hash Table and implement a function ( may be by some reason you want every value to be in a lowercase or uppercase) over each item which will help you do a lot of other things when you are practicing this. So, this code is just to show that this is one way to do this but as I mentioned that this is not one of the best way to this sort of work. Use pointers instead.
Search & Size Operation
IsEmpty Operation
In the example above, I am using a very simple Hash Function which is β
β οΈ In the function above, I am using a prime number. I know a lot of you are scratching their heads that why I used this. Well, it is playing a great role here.
There are a lot of ways you can design your own Hash Functions but no matter how complex you make you Hash Function but there is always high possibility that they will face one issue and that is β
π€ Hash Table Collisions π€
β¦means when Hash Function returns same hash for more than one values.
There are various solutions to this problem β
Separate Chaining, etcβ¦
but in this post, we will go through one of major of them β Separate chaining.
In this method, the hash table will contain links to linked-lists and we will search and insert the item by iterating over these linked-lists.
Put
Remove
Contains
Size
IsEmpty
Traverse
Hash Table before all operations
Put Operation
Remove Operation
Contains Opeartion
Size & IsEmpty Operation
πΉ πΉ πΉ
Deletion in Separate Chaining Method β
LeetCode β
GeekForGeeks β
HackerEarth β