intro to hash tables

12
The answer to your interview question is probably a hash table intro to hash tables Amy Hua

Upload: amy-hua

Post on 29-Jun-2015

313 views

Category:

Education


8 download

DESCRIPTION

Intro to Hash Tables using a Phonebook example.

TRANSCRIPT

Page 1: Intro to Hash tables

The answer to your interview question is probably a hash table

intro to hash tables

Amy Hua

Page 2: Intro to Hash tables

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)

Page 3: Intro to Hash tables

Example applications

Page 4: Intro to Hash tables

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?

Page 5: Intro to Hash tables

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.

Page 6: Intro to Hash tables

For example

In a phone book, how do you know Jane Smith is on page 245?

LookUpPageByLastName(“Smith”) = page 245

hash function

Page 7: Intro to Hash tables

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

Page 8: Intro to Hash tables

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.

Page 9: Intro to Hash tables

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?

Page 10: Intro to Hash tables

CollisionsWell what do you do when you see multiple names on the same page in a phone book?

You go through alinked list

Page 11: Intro to Hash tables

You now know how to use a phone book.. again

Page 12: Intro to Hash tables

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