Hash table
You should use a hash table whenever you need a constant time access to an element in a collection.
There are two types of hash tables. A hash set keeps values and tells whether a value is in it. In some languages, a built-in implementation is called Set.
A hash map keeps pairs of a key and a value and gives the value of a key. In some languages, a built-in implementation is called Dictionary.
Time complexity
| operation | time |
|---|---|
| add an element | on average |
| look up an element | on average |
| remove an element | on average |
Implementation
We will implement a hash set as an example, but a hash map works the same way, except that it also keeps a value next to every key.
Hash function
A hash set stores its elements in an array where each element gets its own index according to its value with a hash function.
A hash function turns a value into a number, and it always gives the same number for the same value. This way, using the same hash function, we can always know at which index the element is and access it in constant time.
Programming languages usually have built-in hash functions, but as an example we can assume some simple hash function that returns the length of a string, so hash("cat") is 3.
The hash can be bigger than the array, so we take it modulo the array length to get an index within its bounds.
Collisions
What if different values produce the same hash? In this case we should store both of them at the same index in one list. So the access to this element would iterate the whole list at that index.
This is why we say it is on average, because in the worst case, when all the elements land on the same index, the time complexity is , though it is usually avoided with a good hash function.
Growth
With more elements added, more collisions will happen and it will get slower. So when the number of elements approaches the array's size, we should migrate all the elements to a new, bigger array.
Build it
Implement add, contains and remove in the class below.
Use hash and grow functions that are already implemented. Call grow from add when the set holds more than 3/4 of the total capacity.