intro to hash tables
DESCRIPTION
Intro to Hash Tables using a Phonebook example.TRANSCRIPT
The answer to your interview question is probably a hash table
intro to hash tables
Amy Hua
Why hash tables?Great for quickly looking something up. Usually faster than arrays or most anything else.Big O Performance: O(1) to O(n)
Example applications
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?
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.
For example
In a phone book, how do you know Jane Smith is on page 245?
LookUpPageByLastName(“Smith”) = page 245
hash function
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
Example hash function
Given keyskeys: Lizzie McGuire
Fiona Apple James Bond
Index them by converting their names to integersLizzie McGuire 13223Fiona Apple 12342James Bond 23523
Divide their numbers by a large enough number (modulo)Lizzie McGuire 3,223 % 1000 = 3 remainder 0.223Fiona Apple 4,342 % 1000 = 4 remainder .342James 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.
CollisionsSometimes, 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?
CollisionsWell what do you do when you see multiple names on the same page in a phone book?
You go through alinked list
You now know how to use a phone book.. again
Sources
• http://www.cs.uregina.ca/Links/class-info/210/Hash/
References• http://www.youtube.com/watch?
v=MfhjkfocRR0&list=TLxupPRqcHJiw• http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/
notes/07-hashing.pdf• http://courses.csail.mit.edu/6.006/spring11/rec/
rec05.pdf