-
CHAPTER 10MAPS, HASH TABLES, AND SKIP LISTSACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH
DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND
GOLDWASSER (WILEY 2016)
0
1
2
3
4 451-229-0004
981-101-0002
025-612-0001
-
MAPS
β’ A map models a searchable collection of key-value entries
β’ The main operations of a map are for searching, inserting, and deleting items
β’ Multiple entries with the same key are not allowed
β’ Applications:β’ address book
β’ student-record database
β’ Often called associative containers
-
THE MAP ADT
β’ get(k): if the map π has an entry with key π, return its associated value; else, return null
β’ put(k, v): insert entry (π, π£) into the map π; if key π is not already in π, then return null; else, return old value associated with π
β’ remove(k): if the mapπ has an entry with key π, remove it from π and return its associated value; else, return null
β’ size(), isEmpty()
β’ entrySet(): return an iterable collection of the entries in π
β’ keySet(): return an iterable collection of the keys in π
β’ values(): return an iterator of the values in π
-
EXAMPLE
β’ Operation Output Mapβ’ isEmpty() true Γβ’ put(5,A) null (5,A)β’ put(7,B) null (5,A),(7,B)β’ put(2,C) null (5,A),(7,B),(2,C)β’ put(8,D) null (5,A),(7,B),(2,C),(8,D)β’ put(2,E) C (5,A),(7,B),(2,E),(8,D)β’ get(7) B (5,A),(7,B),(2,E),(8,D)β’ get(4) null (5,A),(7,B),(2,E),(8,D)β’ get(2) E (5,A),(7,B),(2,E),(8,D)β’ size() 4 (5,A),(7,B),(2,E),(8,D)β’ remove(5) A (7,B),(2,E),(8,D)β’ remove(2) E (7,B),(8,D)β’ get(2) null (7,B),(8,D)β’ isEmpty() false (7,B),(8,D)
-
LIST-BASED MAP
β’ We can implement a map with an unsorted list
β’ Store the entries in arbitrary order
β’ Complexity of get, put, remove?
β’ π(π) on put, get, and remove
tailheader nodes/positions
entries
9 c 6 c 5 c 8 c
-
DIRECT ADDRESS TABLE MAP IMPLEMENTATION
β’ A direct address table is a map in whichβ’ The keys are in the range [0, π]β’ Stored in an array π of size πβ’ Entry with key π stored in π[π]
β’ Performance:β’ put(k, v), get(k), and remove(k) all take π(1) time
β’ Space - requires space π(π), independent of π, the number of entries stored in the map
β’ The direct address table is not space efficient unless the range of the keys is close to the number of elements to be stored in the map, i.e., unless π is close to π.
-
SORTED MAP
β’ A Sorted Map supports the usual map operations, but also maintains an order
relation for the keys.
β’ Naturally supports β’ Sorted search tables - store dictionary in
an array by non-decreasing order of the
keys
β’ Utilizes binary search
β’ Sorted Map ADT adds the following functionality to a map
β’ firstEntry(), lastEntry() βreturn iterators to entries with the smallest
and largest keys, respectively
β’ ceilingEntry(k), floorEntry(k) β return an iterator
to the least/greatest key value greater
than/less than or equal to π
β’ lowerEntry(k), higherEntry(k) β return an
iterator to the greatest/least key value
less than/greater than π
β’ etc
-
EXAMPLE OF ORDERED MAP: BINARY SEARCH
β’ Binary search performs operation get(k) on an ordered search table
β’ similar to the high-low game
β’ at each step, the number of candidate items is halved
β’ terminates after a logarithmic number of steps
β’ Exampleget(7)
1 3 4 5 7 8 9 11 14 16 18 19
1 3 4 5 7 8 9 11 14 16 18 19
1 3 4 5 7 8 9 11 14 16 18 19
1 3 4 5 7 8 9 11 14 16 18 19
0
0
0
0
ml h
ml h
ml h
l=m =h
-
SIMPLE MAP IMPLEMENTATION SUMMARY
put(k, v) get(k) Space
Unsorted list π(π) π(π) π(π)
Direct Address Table π(1) π(1) π(π)
Sorted Search Table
(Naturally supported Sorted Map)
π(π) π(log π) π(π)
-
DEFINITIONS
β’ A set is an unordered collection of elements, without duplicates that typically supports efficient membership tests.
β’ Elements of a set are like keys of a map, but without any auxiliary values.
β’ A multiset (also known as a bag) is a set-like container that allows duplicates.
β’ A multimap (also known as a dictionary) is similar to a traditional map, in that it associates values with keys; however, in a multimap the same key can be
mapped to multiple values.
β’ For example, the index of a book maps a given term to one or more locations at which the term occurs.
-
SET ADT
-
GENERIC MERGING
β’ Generalized merge of two sorted lists A and B
β’ Template method genericMerge
β’ Auxiliary methodsβ’ aIsLess
β’ bIsLess
β’ bothAreEqual
β’ Runs in π(ππ΄ + ππ΅) time provided the auxiliary methods run in π(1) time
Algorithm genericMerge(A, B)
Input: Sets A,B as sorted lists
Output: Set π1. π β β 2. while Β¬π΄.isEmpty()β§ Β¬π΅.isEmpty() do3. π β π΄.first(); π β π΅.first()4. if π < π5. aIsLess(a, S) //generic action6. π΄.removeFirst();7. else if π < π8. bIsLess(b, S) //generic action9. π΅.removeFirst()10. else //π = π11. bothAreEqual(a, b, S) //generic action12. π΄.removeFirst(); π΅.removeFirst()13.while Β¬π΄.isEmpty() do14. aIsLess(A.first(), S); π΄.eraseFront()15.while Β¬π΅.isEmpty() do16. bIsLess(B.first(), S); π΅.removeFirst()17.return π
-
USING GENERIC MERGE FOR SET OPERATIONS
β’ Any of the set operations can be implemented using a generic merge
β’ For example:
β’ For intersection: only copy elements that are duplicated in both list
β’ For union: copy every element from both lists except for the duplicates
β’ All methods run in linear time
-
MULTIMAP
β’ A multimap is similar to a map, except that it can store multiple entries with the same key
β’ We can implement a multimap π by means of a map πβ²
β’ For every key π in π, let πΈ(π) be the list of entries of π with key π
β’ The entries of πβ² are the pairs (π, πΈ(π))
-
MULITMAPS
-
HASH TABLES
-
INTUITIVE NOTION OF A MAP
β’ Intuitively, a map π supports the abstraction of using keys as indices with a syntax such as π π .
β’ As a mental warm-up, consider a restricted setting in which a map with π items uses keys that are known to be integers in a range from 0 to π β 1, for some
π β₯ π.
-
MORE GENERAL KINDS OF KEYS
β’ But what should we do if our keys are not integers in the range from 0 to πβ1?
β’ Use a hash function to map general keys to corresponding indices in a table.
β’ For instance, the last four digits of a Social Security number.
01234 451-229-0004
981-101-0002
025-612-0001
β¦
-
HASH TABLES
β’ A Hash function β π β [0,π β 1]
β’ The integer β(π) is referred to as the hash value of key π
β’ Example - β π = π mod π could be a hash function for integers
β’ Hash tables consist ofβ’ A hash function β
β’ Array π΄ of size π (either to an element itself or to a βbucketβ)
β’ Goal is to store elements π, π£ at index π = β π
-
ISSUES WITH HASH TABLES
β’ Issues
β’ Collisions - some keys will map to the same index of H (otherwise we have a Direct Address Table).
β’ Chaining - put values that hash to same location in a linked list (or a βbucketβ)
β’ Open addressing - if a collision occurs, have a method to select another location in the table.
β’ Load factor
β’ Rehashing
-
EXAMPLE
β’ We design a hash table for a Map storing items (SSN, Name), where
SSN (social security number) is a
nine-digit positive integer
β’ Our hash table uses an array of sizeπ = 10,000 and the hash function
β π = last four digits of π
0
1
2
3
4
9997
9998
9999
β¦451-229-0004
981-101-0002
200-751-9998
025-612-0001
-
HASH FUNCTIONS
β’ A hash function is usually specified as the composition of two functions:
β’ Hash code:β1: keys integers
β’ Compression function:β2: integers [0, π β 1]
β’ The hash code is applied first, and the compression function is applied
next on the result, i.e.,
β π = β2 β1 π
β’ The goal of the hash function is to βdisperseβ the keys in an apparently
random way
-
HASH CODES
β’ Memory address:β’ We reinterpret the memory address of the
key object as an integer
β’ Good in general, except for numeric and string keys
β’ Integer cast:β’ We reinterpret the bits of the key as an
integer
β’ Suitable for keys of length less than or equal to the number of bits of the integer type (e.g.,
byte, short, int and float in C++)
β’ Component sum:β’ We partition the bits of the key into
components of fixed length (e.g., 16 or
32 bits) and we sum the components
(ignoring overflows)
β’ Suitable for numeric keys of fixed length greater than or equal to the
number of bits of the integer type (e.g.,
long and double in C++)
-
HASH CODES
β’ Polynomial accumulation:β’ We partition the bits of the key into a
sequence of components of fixed length
(e.g., 8, 16 or 32 bits)
π0π1β¦ππβ1
β’ We evaluate the polynomialπ π§ = π0 + π1π§ + π2π§
2 +β―+ ππβ1π§πβ1
at a fixed value z, ignoring overflows
β’ Especially suitable for strings (e.g., the choice z = 33 gives at most 6 collisions on a
set of 50,000 English words)
β’ Cyclic Shift:
β’ Like polynomial accumulation except use bit shifts instead of multiplications
and bitwise or instead of addition
β’ Can be used on floating point numbers as well by converting the
number to an array of characters
-
COMPRESSION FUNCTIONS
β’ Division:
β’ β2 π = π mod π
β’ The size N of the hash table is usually chosen to be a prime
β’ The reason has to do with number theory and is beyond the scope of this
course
β’ Multiply, Add and Divide (MAD):
β’ β2 π = ππ + π mod π
β’ π and π are nonnegative integers such that
π mod π β 0
β’ Otherwise, every integer would map to the same value π
-
COLLISION RESOLUTION WITHSEPARATE CHAINING
β’ Collisions occur when different elements are mapped to the same
cell
β’ Separate Chaining: let each cell in the table point to a linked list of
entries that map there
β’ Chaining is simple, but requires additional memory outside the table
0
1
2
3
4 451-229-0004 981-101-0004
025-612-0001
-
EXERCISESEPARATE CHAINING
β’ Assume you have a hash table π» with π = 9 slots (π΄[0 β 8]) and let the hash function be β π = π mod π
β’ Demonstrate (by picture) the insertion of the following keys into a hash table with collisions resolved by chaining
β’ 5, 28, 19, 15, 20, 33, 12, 17, 10
-
COLLISION RESOLUTION WITHOPEN ADDRESSING - LINEAR PROBING
β’ In Open addressing the colliding item is placed in a different cell of the table
β’ Linear probing handles collisions by placing the colliding item in the next (circularly)
available table cell. So the πth cell checked is:β π, π = β π + π mod π
β’ Each table cell inspected is referred to as a βprobeβ
β’ Colliding items lump together, causing future collisions to cause a longer probe sequence
β’ Example:
β’ β π = π mod 13
β’ Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in this order
0 1 2 3 4 5 6 7 8 9 10 11 12
41 18 44 59 32 22 31 73
0 1 2 3 4 5 6 7 8 9 10 11 12
-
SEARCH WITH LINEAR PROBING
β’ Consider a hash table A that uses linear probing
β’ get(k)β’ We start at cell β π
β’ We probe consecutive locations until one of the following occurs
β’ An item with key π is found, or
β’ An empty cell is found, or
β’ π cells have been unsuccessfully probed
Algorithm get(k)
1. π β β π2. π β 03. repeat4. π β π΄ π5. if π β β 6. return ππ’ππ7. else if π.key()= π8. return π9. else10. π β π + 1 mod π11. π β π + 112. until π = π13. return ππ’ππ
-
UPDATES WITH LINEAR PROBING
β’ To handle insertions and deletions, we introduce a special object, called
DEFUNCT, which replaces deleted
elements
β’ remove(k)β’ We search for an item with key π
β’ If such an item π, π£ is found, we replace it with the special item DEFUNCT
β’ Else, we return null
β’ put(k, v)
β’ We start at cell β(π)
β’ We probe consecutive cells until one of the following occurs
β’ A cell π is found that is either empty or stores DEFUNCT, or
β’ π cells have been unsuccessfully probed
-
EXERCISEOPEN ADDRESSING β LINEAR PROBING
β’ Assume you have a hash table π» with π = 11 slots (π΄[0 β 10]) and let the hash function be β π = π mod π
β’ Demonstrate (by picture) the insertion of the following keys into a hash table with collisions resolved by linear probing.
β’ 10, 22, 31, 4, 15, 28, 17, 88, 59
-
COLLISION RESOLUTION WITHOPEN ADDRESSING β QUADRATIC PROBING
β’ Linear probing has an issue with clustering
β’ Another strategy called quadratic probing uses a hash functionβ π, π = β π + π2 mod π
for π = 0, 1,β¦ ,π β 1
β’ This can still cause secondary clustering
-
COLLISION RESOLUTION WITHOPEN ADDRESSING - DOUBLE HASHING
β’ Double hashing uses a secondary hash function β2(π) and handles collisions by placing an item in the first available cell of
the series
β π, π = β1 π + πβ2 π mod π
for π = 0, 1, β¦ , π β 1
β’ The secondary hash function β2 π cannot have zero values
β’ The table size π must be a prime to allow probing of all the cells
β’ Common choice of compression map for the secondary hash function:
β2 π = π β π mod π
where
β’ π < π
β’ π is a prime
β’ The possible values for β2 π are 1, 2, β¦ , π
-
PERFORMANCE OF HASHING
β’ In the worst case, searches, insertions and removals on a hash table take π π time
β’ The worst case occurs when all the keys inserted into the map collide
β’ The load factor πΌ = ππ
affects the performance of
a hash table
β’ Assuming that the hash values are like random numbers, it can be shown that the expected number
of probes for an insertion with open addressing is1
1 β πΌ=1
1 β π π=1
π β π π
=π
π β π
β’ The expected running time of all the Map ADT operations in a hash table is π 1
β’ In practice, hashing is very fast provided the load factor is not close to 100%
β’ Applications of hash tablesβ’ Small databases
β’ Compilers
β’ Browser caches
-
UNIFORM HASHING ASSUMPTION
β’ The probe sequence of a key π is the sequence of slots probed when looking for π
β’ In open addressing, the probe sequence is β π, 0 , β π, 1 , β¦ , β π,π β 1
β’ Uniform Hashing Assumption
β’ Each key is equally likely to have any one of the π! permutations of {0, 1, β¦ ,π β 1} as is probe sequence
β’ Note: Linear probing and double hashing are far from achieving Uniform Hashing
β’ Linear probing: π distinct probe sequences
β’ Double Hashing: π2 distinct probe sequences
-
PERFORMANCE OF UNIFORM HASHING
β’ Theorem: Assuming uniform hashing and an open-address hash table with load
factor πΌ =π
π< 1, the expected number of probes in an unsuccessful search is
at most 1
1βπΌ.
β’ Exercise: compute the expected number of probes in an unsuccessful search in
an open address hash table with πΌ =1
2, πΌ =
3
4, and πΌ =
99
100.
-
ON REHASHING
β’ Keeping the load factor low is vital for performance
β’ When resizing the table:
β’ Reallocate space for the array (of size that is a prime)
β’ Design a new hash function (new parameters) for the new array size (practically, change the mod)
β’ For each item you reinsert into the table rehash
-
SUMMARY MAPS (SO FAR)
put(k, v) get(k) Space
Unsorted list π(π) π(π) π(π)
Direct Address Table π(1) π(1) π(π)
Sorted Search Table
(Naturally supported Sorted Map)
π(π) π(log π) π(π)
Hashing
(chaining)ππ
πππ
ππ(π + π)
Hashing
(open addressing)π1
1 βππ
π1
1 βππ
π(π)
-
SKIP LISTS
+-
S0
S1
S2
S3
+- 10 362315
+- 15
+- 2315
-
RANDOMIZED ALGORITHMS
β’ A randomized algorithm controls its execution through random selection (e.g., coin tosses)
β’ It contains statements like:π β randomBit()
if π = 0
do somethingβ¦
else //π = 1
do something elseβ¦
β’ Its running time depends on the outcomes of the βcoin tossesβ
β’ Through probabilistic analysis we can derive the expected running time of a randomized algorithm
β’ We make the following assumptions in the analysis:β’ the coins are unbiased
β’ the coin tosses are independent
β’ The worst-case running time of a randomized algorithm is often large but has very low probability (e.g., it occurs
when all the coin tosses give βheadsβ)
β’ We use a randomized algorithm to insert items into a skip list to insert in expected π(log π)βtime
β’ When randomization is used in data structures they are referred to as probabilistic data structures
-
WHAT IS A SKIP LIST?
β’ A skip list for a set S of distinct (key, element) items is a series of lists π0, π1, β¦ , πβ
β’ Each list ππ contains the special keys +β and ββ
β’ List π0 contains the keys of π in non-decreasing order
β’ Each list is a subsequence of the previous one, i.e.,π0 β π1 β β― β πβ
β’ List πβ contains only the two special keys
β’ Skip lists are one way to implement the Ordered Map ADT
β’ Java applet
56 64 78 +31 34 44- 12 23 26
+-
+31-
64 +31 34- 23
S0
S1
S2
S3
http://www.cs.umd.edu/class/spring2002/cmsc420-0401/demo/SkipList2/
-
IMPLEMENTATION
β’ We can implement a skip list with quad-nodes
β’ A quad-node stores:β’ (Key, Value)
β’ links to the nodes before, after, below, and above
β’ Also, we define special keys +β and ββ, and we modify the key comparator to handle them
x
quad-node
-
SEARCH - GET(K)
β’ We search for a key π in a skip list as follows:β’ We start at the first position of the top list β’ At the current position π, we compare π with π¦ β π. next(). key()π₯ = π¦: we return π. next(). value()π₯ > π¦: we scan forwardπ₯ < π¦: we drop down
β’ If we try to drop down past the bottom list, we return null
β’ Example: search for 78
+-
S0
S1
S2
S3
+31-
64 +31 34- 23
56 64 78 +31 34 44- 12 23 26
-
EXERCISESEARCH
β’ We search for a key π in a skip list as follows:β’ We start at the first position of the top list β’ At the current position π, we compare π with π¦ β π. next(). key()π₯ = π¦: we return π. next(). value()π₯ > π¦: we scan forwardπ₯ < π¦: we drop down
β’ If we try to drop down past the bottom list, we return NO_SUCH_KEY
β’ Ex 1: search for 64: list the (ππ, node) pairs visited and the return value
β’ Ex 2: search for 27: list the (ππ, node) pairs visited and the return value
+-
S0
S1
S2
S3
+31-
64 +31 34- 23
56 64 78 +31 34 44- 12 23 26
-
INSERTION - PUT(K, V)
β’ To insert an item (π, π£) into a skip list, we use a randomized algorithm:β’ We repeatedly toss a coin until we get tails, and we denote with π the number of times the coin came up heads
β’ If π β₯ β, we add to the skip list new lists πβ+1, β¦ , ππ+1 each containing only the two special keys
β’ We search for π in the skip list and find the positions π0, π1, β¦ , ππ of the items with largest key less than π in each list π0, π1, β¦ , ππ
β’ For π β 0,β¦ , π, we insert item (π, π£) into list ππ after position ππ
β’ Example: insert key 15, with π = 2
+-
S0
S1
S2
S3
+- 10 362315
+- 15
+- 2315
+- 10 36
+-
23
23 +-
S0
S1
S2
p0
p1
p2
-
DELETION - REMOVE(K)
β’ To remove an item with key π from a skip list, we proceed as follows:
β’ We search for π in the skip list and find the positions π0, π1, β¦ , ππ of the items with key π, where position ππ is in list ππ
β’ We remove positions π0, π1, β¦ , ππ from the lists π0, π1, β¦ , ππ
β’ We remove all but one list containing only the two special keys
β’ Example: remove key 34
- +4512
- +
23
23- +
S0
S1
S2
- +
S0
S1
S2
S3
- +4512 23 34
- +34
- +23 34p0
p1
p2
-
SPACE USAGE
β’ The space used by a skip list depends on the random bits used by each invocation of
the insertion algorithm
β’ We use the following two basic probabilistic facts:
β’ Fact 1: The probability of getting πconsecutive heads when flipping a coin is
1
2π
β’ Fact 2: If each of π items is present in a set with probability π, the expected size of the set is ππ
β’ Consider a skip list with π itemsβ’ By Fact 1, we insert an item in list ππ with
probability 1
2π
β’ By Fact 2, the expected size of list ππ is π
2π
β’ The expected number of nodes used by the skip list is
π=0
βπ
2π= π
π=0
β1
2π< 2π
β’ Thus the expected space is π 2π
-
HEIGHT
β’ The running time of find π , put π, π£ , and erase π operations are affected by the height β of the skip list
β’ We show that with high probability, a skip list with π items has height π log π
β’ We use the following additional probabilistic fact:
β’ Fact 3: If each of π events has probability π, the probability that at least one event occurs
is at most ππ
β’ Consider a skip list with π itemsβ’ By Fact 1, we insert an item in list ππ with
probability 1
2π
β’ By Fact 3, the probability that list ππ has at least one item is at most
π
2π
β’ By picking π = 3 log π, we have that the probability that π3 log π has at least one
item is
at most π
23 log π=π
π3=1
π2
β’ Thus a skip list with π items has height at most 3 log π with probability at least 1 β
1
π2
-
SEARCH AND UPDATE TIMES
β’ The search time in a skip list is proportional toβ’ the number of drop-down steps
β’ the number of scan-forward steps
β’ The drop-down steps are bounded by the height of the skip list and thus are π log πexpected time
β’ To analyze the scan-forward steps, we use yet another probabilistic fact:
β’ Fact 4: The expected number of coin tosses required in order to get tails is 2
β’ When we scan forward in a list, the destination key does not belong to a higher list
β’ A scan-forward step is associated with a former coin toss that gave tails
β’ By Fact 4, in each list the expected number of scan-forward steps is 2
β’ Thus, the expected number of scan-forward steps is π(log π)
β’ We conclude that a search in a skip list takes π log π expected time
β’ The analysis of insertion and deletion gives similar results
-
EXERCISE
β’ You are working for ObscureDictionaries.com a new online start-up which specializes in sci-fi languages. The CEO wants your team to describe a data structure which will
efficiently allow for searching, inserting, and deleting new entries. You believe a skip
list is a good idea, but need to convince the CEO. Perform the following:
β’ Illustrate insertion of βX-wingβ into this skip list. Randomly generated (1, 1, 1, 0).
β’ Illustrate deletion of an incorrect entry βEnterpriseβ
β’ Argue the complexity of deleting from a skip list
- +YodaBoba Fett
- +
Enterprise
Enterprise- +
S0
S1
S2
-
SUMMARY
β’ A skip list is a data structure for dictionaries that uses a randomized
insertion algorithm
β’ In a skip list with π items
β’ The expected space used is π π
β’ The expected search, insertion and deletion time is π(log π)
β’ Using a more complex probabilistic analysis, one can show that these
performance bounds also hold with
high probability
β’ Skip lists are fast and simple to implement in practice