4. For example
• Say you have an array of ~100 items
– To look up item at position 3:
• myarray[3]
• O(1)
• But how do you know that the item you’re
looking for is in position 3?
5. For example
In a phone book, how do you know Jane Smith is on page 245?
You probably used an index (last name: Smith) to find the page or range of
pages Jane Smith would be located on.
6. For example
In a phone book, how do you know Jane Smith is on page 245?
LookUpPageByLastName(“Smith”) = page 245
hash function
7. If you know how to use a phone book,
you know how to use a hash table
Hash table: data structure for quickly looking things up.
Given some key, we can apply a hash function to it to find
the index in the array that we want to access.
hash function: takes a key returns an index in the array
LookUpPageByLastName(“Smith”) = 245
hash function key index
8. Example hash function
Given keys
keys: Lizzie McGuire
Fiona Apple
James Bond
Index them by converting their names to integers
Lizzie McGuire 13223
Fiona Apple 12342
James Bond 23523
Divide their numbers by a large enough number (modulo)
Lizzie McGuire 3,223 % 1000 = 3 remainder 0.223
Fiona Apple 4,342 % 1000 = 4 remainder .342
James Bond 9,523 % 1000 = 9 remainder .523
Hash table: stores the key (used to find the index) along with the associated value we’re looking up.
9. Collisions
Sometimes, more than one name is on a given page: multiple elements can
have the same index. In other words, collisions can occur in our hash table.
How do you handle collisions?
10. Collisions
Well what do you do when you see multiple names on the same page in a
phone book?
You go through a
linked list