Hashing and Hash Tables
Transcript
Imagine that you have a personal library with one million books, positioned quite randomly. Searching for a specific book would be a pain, you may need to go through hundreds of thousands of books before finding the one you're searching for. We call this linear search, walking through books one by one until finding the right one. So the more you have books, the more searching time increases. But what if you had a powerful tool that, regardless of how many books you have, just by giving it the title of your book, gives you the exact position in the library, without traversing all previous books. This concept exists in algorithms and data structures, it's called: hashing, and it's what we will discuss in this crash course. Get ready to take notes and to ask questions in comments if you didn't understand something. What is hashing? Hashing is simply the process of converting a key to a fixed-size value.
For example the key can be the string "inside code", it gets converted for example to the number 29. The result of this conversion, the result of hashing, is called a hash. Two questions may come in your mind right now: why? and how? Why would we need hashing? And how would we calculate the hash of a key? For example how did we go from the string "inside code" to 29. Why would we need hashing? Let's take our initial example, storing books
in a library. Our library has a capacity of 1000000 books, so we have the position 0, the position 1, and so on until 999999. We spoke about a powerful tool that, just by giving it the title of a book, gives you its position in the library. What does this tool use? You guessed it, it uses hashing! The key is the book's title, as a string, and the produced hash represents the position of that book in the library. So by using hashing,
we can find the position where should a specific book be, no matter how many books there are. However, one important condition, is that when we insert that book, we should also follow the position given by hashing, to find it in the right place when we search for it later. And this kind of structure is called a hash table. A hash table is a data structure that stores key/value pairs. Values are stored in an array of slots, and to find the index of the value associated to a key, we just use hashing, we take our key, we use hashing, and it gives us the index of its value in the array. With our initial example, a key is the title of a book, a value is the book itself, the array is the library, and an index in the array is a position in the library. But we don't know much about this powerful tool, what does it utilize? It uses a hash function, a function that takes as input a
key, does some computations, and returns the hash of that key, it's what we use in the hashing process. But how does it work? Well, we don't have only one hash function, we have an infinite number of hash functions, we can even create one, that's what we gonna do right now. We have a string key and its hash should represent the index of its value in an array of m slots, so as output we should get a number from 0 to m-1. m is the number of slots. We
can think of simply adding together the ASCII code of each character, then returning the result modulo m to get a value between 0 and m-1. For example for the key "inside code" and m = 30, here's the ASCII code of each character. By doing the sum we get 1079, and modulo 30 we get 29, so by using this hash function on the key "inside code", we got a hash of 29. It means that the value associated to the key "inside code" is at the index 29.
We created this simple hash function, and it's working, but is it a good one? That's another story, we will talk about it later. And by the way, a hash function must be deterministic, it means that for the same key, it should always return the same hash, which is logical because if it wasn't deterministic, the hash we get when searching for a value could be different from the one we get when inserting that value, so we wouldn't get the right position.
--Okay now you know what is hashing, what is a hash, what is a hash table, what is a hash function, we can discuss some practical use cases of the hash table. We can use a hash table when we want to create a phone agenda. The key is the person's name for example, and the value is the phone number. So if we want the phone number of someone, we just hash his name, and we get the index from where we can get the phone number. Another example is a word counter for a text, we want to store the number of occurrences of each word. So the key is a word, and the value is an integer that represents its number of occurrences. Last example, we can use it to implement a dictionary. A dictionary contains words and their definitions, so the key is a word, and the value is its definition. And if we want the definition of a word, we hash it, and we get the index of its definition. Those
were some examples of when would we think of using a hash table, let's now take the first example and see what happens when we perform some operations, we want to see what happens in our phone agenda example. Let's insert some key/value pairs. We have "John Smith" whose number is this one. We hash the string "John Smith" by adding ASCII codes of all characters then modulo 30, we get 18, so the value, the number of "John Smith" will be at index 18. Next pair, we have "Samy Sterious", whose number is this one. We hash the string "Samy Sterious", we get 14, so we put his number at the index 14. Next pair "Sarah Plick", by hashing we get 6, we put her number at index 6. Next pair, "Khaled Anas", whose number is this one. By hashing the key we get 14, we put the number at index 14. But wait, we already have a value at index 14, the number of "Samy Sterious", what happened here? Here
we got two different keys that gave the same hash, hence the same index. And this is what we call, a collision. A collision is when two different keys in a hash table produce the same hash. We can agree that it's an issue, how will we put two different values in a same spot? For that we need to handle collisions. And I'm gonna show you 2 ways to do so. First one is separate chaining. We actually cannot put more than one value in the same spot,
but what we can do, is that instead of having a single value in a spot, a spot would contain a linked list of values, where we can put all the values associated to keys whose the hash is the index of that spot. So for example if we're storing 3 keys whose the hash is 13, their values will be a in a linked list at the index 13, the index 13 will hold a linked list of length 3 where each node contains a value. Back to our example, this time in
our spots we have a linked list. At the beginning all linked lists are empty because we didn't insert yet. Now we insert the same pairs, "John Smith", hash is 18, we add a node to the linked list at index 18 where we put his number. Next pair, "Samy Sterious", whose hash is 14, we add a node. Next pair, "Sarah Plick", whose hash is 6, we add a node there. Then "Khaled Anas", by hashing we get 14, the same key as "Samy Sterious", so we have a collision. But with separate chaining, no problem, we just add a node to the linked list of the index 14, we handled the collision. However, one important detail. Imagine that I want the number of "Khaled Anas", I hash his name, I get 14, so I know that his number is in one of the nodes of the linked list at index 14. But, which one? We have no way to know which one of these two numbers belongs to "Khaled Anas", we know that it's one of
them, but we don't know which one exactly. And this is why storing the value itself in a node isn't enough, we also need to store the key, yes, to be able to find the value we're searching for when there are collisions. Now if we want to know the number of "Khaled Anas", we hash, we find 14, and in the linked list of the index 14, we search for the node where we can find "Khaled Anas" as key, because its value is his number. That was for separate chaining, but we can also use open addressing. Open addressing doesn't use a list structure for spots, it keeps the principle of having only one value per spot. But, when a collision happens, it searches for alternative spots where to insert or where to find the value, which is called probing. One of ways of probing is linear probing, it keeps moving to the next spot until it finds an empty one, it represents the spot of that value. For example
we have this hash table and want to insert the last pair, "Khaled Anas" and his number. We hash the key, "Khaled Anas", we find 14. But the spot 14 is occupied so we check 15. The spot 15 is also occupied so we check 16. 16 is also occupied so we check 17. 17 is empty, we can put our key/value pair there. Here also we need to store the key as you can see, to be able to find the value we're searching for when there are collisions. Now
we learned some techniques to handle collisions, but it doesn't mean that they're not a problem anymore, we'll see why in time complexity analysis chapter. But can't we just avoid them? Can we have no collisions? Well, most of the time, it's not possible. In the context of hash tables, hashing converts a key to an index from 0 to m-1, where m is the number of slots. So we have only m different hash values, while the number of keys can be infinite, like with strings, we have an infinity of strings. Which means that necessarily, because of the Pigeonhole principle, if we keep inserting, some different keys will share the same spot, which produces collisions. The only case where it's possible to never have collisions is when the number of keys doesn't exceed the size of the hash table. For example if we have 20 keys and 30 spots, and we know that we won't insert keys anymore, we can search
for a hash function that will map those 20 keys to the 30 spots without giving the same spot to more than one key. Such a hash function is called a perfect hash function, what we did here is perfect hashing. But this technique isn't always used, so we can have collisions. However, good news, we can still minimize the number of collisions, by using a good hash function. Imagine that even if we have 30 indexes, so 30 possible hash values, our
hash function produces a hash that is almost always among the first 5 indexes. What's gonna happen is that there will be a lot of collisions because a lot of keys will get a hash that is from 0 to 4. Which is bad, we want to have as less collisions as possible, so it's a bad hash function. With a better hash function, each possible hash value would be produced with roughly the same probability, to distribute inputs as evenly as possible over the different
hash values and avoid collisions as much as possible. As you can see here, we have few collisions because this hash function distributes keys almost evenly over the different hash values, it doesn't condense keys into a small subset of hash values, which creates a lot of collisions. We can say that it's a better hash function. In brief, with a bad hash function, some hash values have a way higher probability to appear than others, which provokes collisions
there, and with a better one, all hash values have almost the same probability to appear, which reduces collisions. Imagine now that we have a hash table of 10 spots and 50 keys to insert. Even by using a very good hash function, we will have a lot of collisions, each spot will contain 5 elements in average, which is bad, we usually want to have at most one or two elements in a spot, not more. The problem here is clearly the lack of space,
even with a good hash function, we cannot fit 50 keys in 10 spots without having a lot of collisions. And here comes rehashing. Rehashing consists of creating a new table with a higher number of spots, for example the double, then inserting the pairs in the new table. Doing so obviously decreases the number of collisions because it distributes keys over a larger range of values. But the question is when to rehash? An important measure to take into
consideration is how full our hash table is, we can for example calculate it with the ratio n/m, where n is the number of inserted elements, and m the number of slots. For example here n is 21 and m is 30, we get a ratio of 0.7. And there is a small difference for this ratio between using separate chaining and open addressing. When using open addressing, each spot contains at most one element, so n can never exceed m, this why the ratio n/m can never exceed
1, it's between 0 and 1, 0 when the hash table is totally empty, and 1 when all spots are occupied. But in separate chaining, a same spot can store multiple elements, so n can exceed m, this is why the ratio can be below 1, but it can also be 1.5, 2, 5, whatever. For example in this example we had 50 elements stored in 20 spots, the ratio was 2.5. And the measure we use to know when to rehash is the load factor. We define the load factor
as the maximum allowed value of the ratio n/m before we rehash. For example if we set the load factor to 0.75, then as soon as n/m exceeds 0.75, we rehash. Which will obviously decrease this ratio because we increase m. For example if m is 100, if we have 100 spots, nothing happens when inserting the first 75 elements. But as soon as we insert the element 76, the hash table automatically rehashes. 0.75 is usually a pretty good default load factor, but we can choose one that is lower or higher
if we want to prioritize time or space efficiency, we'll talk more about it in the next part. And the hash function we made before, is it a good hash function? Well, not really, and I'm gonna give you two reasons. The first one is that strings are order-sensitive, the string "abc" is different from the string "acb" for example. But this hash function gives the same hash to both of them, because the sum of ASCII codes of characters remains
the same even if the order is different. Which means that given a set of letters, all their permutations will have the same hash, which is not the best property to have in a hash function. Second problem, rehashing can have no effect on collisions. Imagine that our keys will be strings of at most 20 characters made of alphabetical letters only. The maximum sum of ASCII codes of such strings is 2440, 20 times the highest code of one character
which is 122. It means that with this hash function, in this context, no matter the number of spots, the returned hash cannot exceed 2440. What does it imply? It implies that all spots after 2440 will be useless. So if for example m = 2500 and the ratio exceeds the load factor, then it's time to rehash. But doing so will have no impact, because all new spots will stay empty, the actual hash function cannot reach their index, for
any key, the produced hash cannot exceed 2440. And this is a problem, because if we have too many keys, even if increase the table by rehashing, elements will still be condensed in the spots from 0 to 2440, which causes a lot of collisions that we cannot reduce by rehashing. This is why this simple hash function isn't the best choice, we need one that is a bit more complex and doesn't have these issues. Before moving to time and space
complexity analysis, we need a little recap, I know that this video is quite dense but I think it's necessary to understand hashing and hash tables. First we have hashing, the process of converting a key to a fixed-size value. We have the hash, the code that is produced by the hashing process. We also have the hash table, a data structure that stores key/value pairs in a table of spots, it uses hashing to calculate the index where an element should be located, we use it when we have keys and values that are associated to them, for example a phone agenda or a dictionary. We have the hash function, a deterministic function that is used in hashing, it takes as input a key and calculates its hash. A good hash function is a hash function that respects some important properties, like distributing keys as evenly as possible across the different hash values or being computationally efficient,
which contributes in having a good performance overall when using our hash table. A collision is when two keys in a hash table have the same hash value. To handle them, we have separate chaining, a collision handling technique that works by storing pairs with the same hash value in a linked list at that spot, each node contains a key/value pair. We also have open addressing, another collision handling technique that works by searching for an alternative spot if the actual one is occupied. Then we have perfect hashing, mapping n keys to m hash values with no collisions. We also have rehashing, rehashing consists of creating a new table with a higher number of spots then inserting previously stored elements in it, which reduces collisions. When to apply rehashing is determined by the load factor, the maximum allowed value of the ratio n/m before rehashing. Those were the important
definitions to understand. And by the way, in this video we focused on hashing when being applied to implement hash tables, but it has other applications, we can also use it for example in cryptography. Anyway, in this video we talked about a lot of concepts related to hash tables, but we still didn't really answer an important why question, why would we use a hash table to store key/value pairs, why don't we just store them in a simple array
instead of doing all of this? This is what we will talk about now. As you may know, the need of different data structures is mainly justified by time and/or space efficiency, which is the case here, using a hash table over a simple array is a matter of time efficiency for some operations. Let's understand it by analyzing time and space complexity of the hash table and its main operations. When we speak about the space complexity of a data structure, it means how much space it uses in relation to the number of elements it stores. In the case of a hash table, the space usage grows linearly with the number of elements n, let me tell you why. In a hash table we have two things that determine the space usage, we have the total number of nodes, and the number of spots. Each node represents one element, so we have n nodes. And the number of spots is some constant c times the number
of elements, the constant c depends on the load factor. And the sum of these two is in O(n), the hash table has an O(n) space complexity. For main operations, to analyze their time complexity, we first need to understand what happens exactly, this is why we will analyze them while implementing a hash table in Python. Obviously, this is just for learning purposes, in reality for a general usage hash table, there already exist built-in implementations
in a lot of languages, for example dict in Python, HashMap in Java, and unordered_map in C++. Let's start implementing a simple hash table. For collision handling we will use separate chaining. We first need a class Node, a node contains the key, the value, and the pointer to the next node in the linked list. Here the key is of type string because our hash function can be used on strings only, but a general usage hash table can accept
more types, we'll talk about it later. Now we create a type linked list, it contains the head only. But we need 3 methods to manipulate it, a method to insert a node, a method to search for a node with a particular key, and a method to delete a node with a particular key. We have many ways to insert a node in a linked list, but we only need the simplest one, inserting at the beginning. For that we create a node whose the next node is the actual head, and we set it as the new head of the linked list. For searching a node, we just traverse nodes and return the one whose key is equal to the input key. Otherwise we return null. And for deleting a node, we just search for the node whose next node's key's is the input key and we skip it. We return true if the deletion happened, false otherwise. Now we can create our HashTable class. A hash table has 4 things. A capacity,
which is the number of slots, we can initially set it to 30 like in the example. It also has a size, which is the number of elements stored in it, initially 0. It also has a load factor, we can set it to 0.75 for example. And the array of slots, where each slot contains a linked list, so we create an array of linked lists. For methods, we need a hash function, a function to rehash, a function to insert a key/value pair or update the value of a
key, a function to search for the existence of a key, a function to get the value associated to a key, and a function to delete a key/value pair. For the hash function we will just use the one we used in our examples, it's not the best one for sure but it still works. For rehashing, we save the old slots, we multiply the capacity by 2, we reset size, and we create a new array of slots with the new capacity. But it's empty, we need to insert elements stored previously, this is why we traverse the old slots, and for each node in the slot, we insert that key/value pair in the new array of slots. Next method, inserting. We want to insert a key/value pair, or update the value of the given key if it already exists in the hash table. First step, we calculate the index where it should be by using the hash function. We get the index, we go to the linked list of that index. And here we
have two cases, either our key already exists, or it doesn't. We can know it by using the search function of that linked list. If it exists, then it's an update, we just assign the new value to the existing value of the node of our key. Else, it's an insertion, we use the linked list insert method to insert our key/value pair as a new node. We also increment size, which represents the number of nodes. And important thing, we check if we rehash, so if n/m, the size divided by the capacity, exceeds the load factor, we rehash. And we got our insert method. Let's continue remaining methods before analyzing the time complexity. Next method, searching, we want a function that returns if yes or no the given key exists in the hash table. For that, we calculate the index, we use the linked list search method, and see if it returns a node or if it returns null, if it returns
a result that is not null then our key exists, otherwise it doesn't exist. Next method, getting the value associated to a key. To do so we calculate the index, and search for the node whose the key is the given key. If it exists, we return its value, else we return null because the key doesn't exist in the hash table so it doesn't have a value. Last operation, deleting. We calculate the index, then we use the delete method of the linked list of that index. If
the deletion happened, then we decrement size. We could even have another load factor for when the hash table gets too empty, such that if the ratio n/m goes below it, we rehash by reducing the number of slots. We do so if we want to save space. Okay now we implemented our simple hash table, we can for example use it for the phone agenda example, here are some operations. Let's analyze time complexity now. Inserting a node at the beginning of
a linked list is in O(1) time because we don't traverse nodes. Searching for a node with a given key requires performing a linear search, whose cost depends on the length of the linked list, so its time complexity is O(l), l is the length of the linked list. Deleting a node is also in O(l) because we need to traverse the nodes. For the hash function, hashing a key doesn't require us to traverse elements of the hash table, so its runtime isn't related
to the number of elements in the hash table, the number of elements doesn't affect its runtime, this is why we say that the hash function runs in O(1) time. We can argue that it grows linearly with the key size so it should be O(k) or something, but it's not always the case. For example integers are usually in 32 or 64-bit, which is constant, so hashing an integer is in O(1) time, or when we use a hash function that uses only a fixed number of characters from the key, it's also in O(1). Or when we know that our keys don't exceed a particular size, it's also in O(1). So let's just say that the hash function runs in O(1) time, because the important is that it doesn't get affected by the number of elements in the hash table. Now for insertion, we have hashing, which costs O(1) time. Then searching for a node with the given key in the linked list of that spot. The time required
for this action depends on the number of elements in that linked list, because we will perform a linear search. And this is why collisions affect performance of our hash table, the more we have collisions, the more we have nodes to traverse when searching for the node. Let's put O(l) for now for searching the node, l represents the length of the linked list. If we find the node, we just update the value, which costs O(1) time, but if we don't, we need to insert. Inserting in a linked list as we're doing it costs O(1) time because we're inserting at the head. But if it causes the ratio n/m to go over load factor, we need to rehash, which costs O(n) in average because we need to traverse all elements and insert them. Let's now discuss the value of l. In the best case, we have no collisions at all, so each list has a length of 0 or 1, we get O(1) for searching for the node. And in the
worst case, the linked list contains all the n nodes, the length is then n, we get O(n) for searching for the node. These two cases are quite extreme and very different, which one of them happens in practice? In practice, none of them usually, having no collisions at all is rare and having all nodes in a single spot means that we have a very bad hash function. In practice, we avoid the second case by using a good hash function and rehashing, but we can still have collisions. So in practice, even if we have some collisions that we can't avoid, we try to distribute them in a way that keeps the length of a linked list reasonable, under some constant. It's not guaranteed, but with a good implementation, the length of a single linked list usually doesn't exceed some constant. And this is why we say that searching for the node is in O(1) time in average. Okay this step is in O(1) in average,
but we still have rehashing which is in O(n) in average, so inserting an element is in O(n) in average? No, because even if rehashing costs O(n) in average, it doesn't frequently happen. It happens only when the ratio n/m exceeds the load factor, where we rehash, then we're safe for a lot of insertions where we won't need to rehash. Then again, we rehash, and we're safe for a bunch of insertions. And so on. So even if sometimes inserting
costs O(n) in average because of rehashing, but it happens so infrequently that when we divide the sum of costs of a large number of insertions by the number of insertions, we find that it's in O(1). This is what we call amortized complexity, this part of the insertion process costs O(1) time amortized. We finished analysing what happens when inserting, we found out that inserting an element in a hash table is in O(1) average and amortized
time complexity. This is very important to understand, if you didn't, please ask a question below, don't just continue without understanding why it's in O(1) average and amortized. Let's continue. Next operation is lookup, searching for the existence of a key. For that we calculate the hash, O(1), then perform a linear search on the linked list of that spot, which is in O(1) in average, same logic as for inserting. We get O(1) time in average for lookup. Then
for getting the value of a key, same thing, hashing is in O(1) and searching for the node is in O(1) in average, we get O(1) in average for this operation. Last operation, deleting. Hashing is in O(1), and deleting a node from a linked list requires a linear search, which is in O(1) in average in our case, same logic as for previous operations. In total we get O(1) in average for deleting the pair with a given key. And here you can see the advantage
of using a hash table and why it's a powerful data structure, in the average case, we can insert in O(1) time amortized, search in O(1) time, get the value of a key in O(1) time, and delete in O(1) time, which is time efficient. However, we don't forget that it still suffers from having O(n) time for these operations in the worst case, this is why it's important to have a good implementation, to avoid this worst case. It's also interesting to know how the load factor affects the time and space efficiency of a hash table. Choosing the value of the load factor is a tradeoff between time and space efficiency. Because if we reduce the load factor, the number of spots will be way higher than the number of elements, which is time efficient because we have less collisions, but not space efficient because we have a lot of wasted space. At the opposite, if we increase the load factor, the number
of spots will be lower than the number of elements, we will have less wasted space, which is space efficient, but a lot of collisions because there is less space, which is not time efficient. Now if from this crash course you understood how does a hash table works and why it's fast, you can start using it when programming. It's also widely useful when solving coding problems. A classic problem is the two sum problem, the problem of finding
indices of two elements in an array whose the sum is k. Instead of trying all couples, which is in O(n²) time, we just store in a hash table each element and the index where we've seen it, and as soon as for an element x, we notice that we found k-x before, we return both indices. All that is done in O(n) time. Last thing I wanted to talk about is some properties of the keys and values in a hash table. First one is uniqueness. Keys
in a hash table must be unique, we shouldn't be able to find the same key twice. However, values don't need to be unique, two keys can have the same value with no problem. Second thing, immutability. A key in a hash table must be immutable. Imagine that we have a mutable object, an array for example. Let's suppose that with this state, we get a hash of 56. After it we mutate it by adding a value. The problem is that the array changed, so
if we pass it to the hash function, it may not give 56. And in a hash table, for a same key, the hash function must always return the same hash. Which is not the case here, and this is why we cannot have a mutable object as a key. So as a key we can have an integer, a string, a tuple...etcetera, it's fine, these types are immutable, but we can't have an array or a set for example, these are mutable. But as a value, it's fine, we can have a mutable
object as a value, because we don't hash a value, so a value can be anything, an integer, a string, an array, a hash table, an object...etcetera. In brief, a key must be unique and immutable, which is not necessary for a value. We finally reached the end of this crash course on hashing and hash tables, I tried to cover this topic in detail, I hope that it wasn't too long or too difficult to understand. If you didn't understand something, you can put a comment, and if you enjoyed this crash course, you can support inside code's content, for example by checking the other courses I made. See you in the next lecture.

Ask anything
We've read this whole study set, so questions about it get the best answers.