Intro to Hash tables


Published on

Intro to Hash Tables using a Phonebook example.

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Intro to Hash tables

  1. 1. The answer to your interview question is probably a hash table intro to hash tables Amy Hua
  2. 2. 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)
  3. 3. Example applications
  4. 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. 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. 6. For example In a phone book, how do you know Jane Smith is on page 245? LookUpPageByLastName(“Smith”) = page 245 hash function
  7. 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. 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. 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. 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
  11. 11. You now know how to use a phone book.. again
  12. 12. Sources • info/210/Hash/ References • st=TLxupPRqcHJiw • otes/07-hashing.pdf • 05.pdf