Maps, Hash Tables, Skip Lists, Sets last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets1.

Slides:



Advertisements
Similar presentations
© 2004 Goodrich, Tamassia Skip Lists1 S0S0 S1S1 S2S2 S3S
Advertisements

Skip Lists. Outline and Reading What is a skip list (§9.4) – Operations (§9.4.1) – Search – Insertion – Deletion Implementation Analysis (§9.4.2) – Space.
SKIP LISTS Amihood Amir Incorporationg the slides of Goodrich and Tamassia (2004)
© 2004 Goodrich, Tamassia Hash Tables
© 2004 Goodrich, Tamassia Hash Tables1  
© 2004 Goodrich, Tamassia Maps1. © 2004 Goodrich, Tamassia Maps2 A map models a searchable collection of key-value entries The main operations of a map.
Maps. Hash Tables. Dictionaries. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
Data Structures Lecture 12 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Data Structures Lecture 13 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
© 2004 Goodrich, Tamassia Skip Lists1  S0S0 S1S1 S2S2 S3S3    2315.
CSC311: Data Structures 1 Chapter 9: Maps and Dictionaries Objectives: Map ADT Hash tables –Hash functions and hash code –Compression functions and collisions.
CSC401 – Analysis of Algorithms Lecture Notes 5 Heaps and Hash Tables Objectives: Introduce Heaps, Heap-sorting, and Heap- construction Analyze the performance.
Dictionaries and Hash Tables1  
© 2004 Goodrich, Tamassia Maps1. © 2004 Goodrich, Tamassia Maps2 A map models a searchable collection of key-value entries The main operations of a map.
Hash Tables1 Part E Hash Tables  
Hash Tables1 Part E Hash Tables  
Hash Tables1 Part E Hash Tables  
Skip Lists1 Skip Lists William Pugh: ” Skip Lists: A Probabilistic Alternative to Balanced Trees ”, 1990  S0S0 S1S1 S2S2 S3S3 
Dictionaries 4/17/2017 3:23 PM Hash Tables  
Maps, Hash Tables and Dictionaries Chapter 10.1, 10.2, 10.3, 10.5.
Maps, Dictionaries, Hashing
CS 221 Analysis of Algorithms Data Structures Dictionaries, Hash Tables, Ordered Dictionary and Binary Search Trees.
Hash Tables1   © 2010 Goodrich, Tamassia.
Dictionaries and Hash Tables1 Hash Tables  
© 2004 Goodrich, Tamassia Hash Tables1  
Skip Lists 二○一七年四月二十五日
CHAPTER 9 HASH TABLES, MAPS, AND SKIP LISTS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++,
Map ADT by Dr. Bun Yue Professor of Computer Science CSCI 3333 Data Structures.
2/19/2016 3:18 PMSkip Lists1  S0S0 S1S1 S2S2 S3S3    2315.
Maps1 © 2010 Goodrich, Tamassia. Maps2  A map models a searchable collection of key-value entries  The main operations of a map are for searching, inserting,
© 2004 Goodrich, Tamassia Maps1. © 2004 Goodrich, Tamassia Maps2 A map models a searchable collection of key-value entries The main operations of a map.
Lecture14: Hashing Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Sets and Multimaps 9/9/2017 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia,
Hash Maps Rem Collier Room A1.02 School of Computer Science and Informatics University College Dublin, Ireland.
Hash Tables 1/28/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Maps 1/28/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Hashing (part 2) CSE 2011 Winter March 2018.
Skip Lists S3   S2   S1   S0  
Sorted Maps © 2014 Goodrich, Tamassia, Goldwasser Skip Lists.
Sets and Multimaps 5/9/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia,
Skip Lists 5/10/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Hashing CSE 2011 Winter July 2018.
Dictionaries Dictionaries 07/27/16 16:46 07/27/16 16:46 Hash Tables 
© 2013 Goodrich, Tamassia, Goldwasser
Dictionaries 9/14/ :35 AM Hash Tables   4
Hash Tables 3/25/15 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Skip Lists S3 + - S2 + - S1 + - S0 + -
Objectives Introduce different known sorting algorithms
Sequences 11/12/2018 5:23 AM Sets Sets.
Skip Lists.
Data Structures Maps and Hash.
Skip Lists S3 + - S2 + - S1 + - S0 + -
Hash Tables 11/22/2018 3:15 AM Hash Tables  1 2  3  4
Dictionaries 11/23/2018 5:34 PM Hash Tables   Hash Tables.
Dictionaries and Hash Tables
Skip Lists S3 + - S2 + - S1 + - S0 + -
Copyright © Aiman Hanna All rights reserved
Sorted Maps © 2014 Goodrich, Tamassia, Goldwasser Skip Lists.
Dictionaries < > = /3/2018 8:58 AM Dictionaries
Hash Tables   Maps Dictionaries 12/7/2018 5:58 AM Hash Tables  
CH 9.2 : Hash Tables Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and.
Dictionaries and Hash Tables
Dictionaries 1/17/2019 7:55 AM Hash Tables   4
CH 9.2 : Hash Tables Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++, Goodrich, Tamassia and.
Parasol Lab, Dept. CSE, Texas A&M University
Dictionaries 4/5/2019 1:49 AM Hash Tables  
Maps 4/25/2019 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
CS210- Lecture 17 July 12, 2005 Agenda Collision Handling
CS210- Lecture 16 July 11, 2005 Agenda Maps and Dictionaries Map ADT
Dictionaries and Hash Tables
Presentation transcript:

Maps, Hash Tables, Skip Lists, Sets last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets1

Maps & Dictionaries last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets2

Maps last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 3 A map models a searchable collection of key-value entries The main operations of a map are for searching, inserting, and deleting entries Multiple entries with the same key are not allowed Applications:  address book  student-record database  Ordered maps (dictionaries) allow nearest neighbor queries in addition to the above three (see also Slide 11).

The Map ADT last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 4 get(k): if the map M has an entry with key k, return its associated value; else, return null put(k, v): insert entry (k, v) into the map M; if key k is not already in M, then return null; else, return old value associated with k remove(k): if the map M has an entry with key k, remove it from M and return its associated value; else, return null entrySet(): return an iterable collection of the entries in M keySet(): return an iterable collection of the keys in M values(): return an iterator of the values in M size() isEmpty()

Example OperationOutputMap 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) OperationOutputMap 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) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 5

The Java Map Hierarchy last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 6 «interface» Map ( § ) «interface» Map ( § ) «interface» SortedMap ( § 10.3) «interface» SortedMap ( § 10.3) AbstractMap ( § ) AbstractMap ( § ) AbstractSortedMap ( § 10.3) AbstractSortedMap ( § 10.3) UnsortedTableMap ( § ) UnsortedTableMap ( § ) AbstractHashMap ( § ) AbstractHashMap ( § ) SortedTableMap ( § ) SortedTableMap ( § ) TreeMap (chapter 11) TreeMap (chapter 11) ChainHashMap ( § ) ChainHashMap ( § ) ProbeHashMap (§ ) ProbeHashMap (§ ) (additional subclasses) (additional subclasses)

A Simple List-Based Map We can implement a map using an unsorted list – We store the items of the map in a list S (based on a doubly linked list), in arbitrary order last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 7 trailer header nodes/positions entries 9 c 6 c 5 c 8 c

The get(k) Algorithm Algorithm get(k) B  M.positions() // B is an iterator of the positions in S while B.hasNext() do p  B.next() // the next position in B if p.element().getKey() = kthen return p.element().getValue() return null // there is no entry with key equal to k Algorithm get(k) B  M.positions() // B is an iterator of the positions in S while B.hasNext() do p  B.next() // the next position in B if p.element().getKey() = kthen return p.element().getValue() return null // there is no entry with key equal to k last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 8

The put(k,v) Algorithm Algorithm put(k,v) B  M.positions() While B.hasNext() do p  B.next() if p.element().getKey() = k then t  p.element().getValue() M.set(p,(k,v)) return t// return the old value M.addLast((k,v)) n  n + 1 // increment variable storing number of entries return null// there was no entry with key equal to k Algorithm put(k,v) B  M.positions() While B.hasNext() do p  B.next() if p.element().getKey() = k then t  p.element().getValue() M.set(p,(k,v)) return t// return the old value M.addLast((k,v)) n  n + 1 // increment variable storing number of entries return null// there was no entry with key equal to k last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 9

The remove(k) Algorithm Algorithm remove(k) B  M.positions() While B.hasNext() do p  B.next() if p.element().getKey() = k then t  p.element().getValue() M.remove(p) n  n – 1 // decrement number of entries return t// return the removed value return null// there is no entry with key equal to k Algorithm remove(k) B  M.positions() While B.hasNext() do p  B.next() if p.element().getKey() = k then t  p.element().getValue() M.remove(p) n  n – 1 // decrement number of entries return t// return the removed value return null// there is no entry with key equal to k last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 10

Performance of a List-Based Map Performance: – put, get and remove take O(n) time since in the worst case we traverse the entire sequence to look for an item with the given key The unsorted list implementation is effective only for maps of small size or for maps in which puts are the most common operations, while searches and removals are rarely performed (e.g., historical record of logins to a workstation) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 11

Hash Tables   last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets12

Recall the Map ADT last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets13 get(k): if the map M has an entry with key k, return its associated value; else, return null put(k, v): insert entry (k, v) into the map M; if key k is not already in M, then return null; else, return old value associated with k remove(k): if the map M has an entry with key k, remove it from M and return its associated value; else, return null entrySet(): return an iterable collection of the entries in M keySet(): return an iterable collection of the keys in M values(): return an iterator of the values in M size() isEmpty()

Intuitive Notion of a Map last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets14 Intuitively, a map M supports the abstraction of using keys as indices with a syntax such as M[k]. As a mental warm-up, consider a restricted setting in which a map with n items uses keys that are known to be integers in a range from 0 to N − 1, for some N ≥ n.

More General Kinds of Keys But what should we do if our keys are not integers in the range from 0 to N – 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. last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 15   …

Hash Functions & Hash Tables A hash function h maps keys of a given type to integers in a fixed interval [0, N - 1] Example: h(k) = k mod N is a hash function for integer keys The integer h(k) is called the hash value of key k A hash function h maps keys of a given type to integers in a fixed interval [0, N - 1] Example: h(k) = k mod N is a hash function for integer keys The integer h(k) is called the hash value of key k A hash table for a given key type consists of – Hash function h – Array (called table) of size N When implementing a map with a hash table, the goal is to store item (k, v) at index i = h(k) A hash table for a given key type consists of – Hash function h – Array (called table) of size N When implementing a map with a hash table, the goal is to store item (k, v) at index i = h(k) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets16

Example We design a hash table for a map storing entries as (key, value)  (SIN, Name), where SIN (social insurance number) is a ten-digit positive integer Our hash table uses an array of size N = 10,000 and the hash function h(k) = last four digits of k last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets17     …

Hash Functions A hash function is usually composed of two functions: Hash code: h 1 : keys  integers Compression function: h 2 : integers  [0, N - 1] The hash code is applied first, and the compression function is applied next on the result, i.e., h(x) = h 2 (h 1 (x)) The goal of the hash function is to “disperse” the keys in an apparently random way last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets18

Hash Codes Memory address:  We reinterpret the memory address of the key object as an integer (default hash code of all Java objects)  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 Java) 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 Java) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets19

Hash Codes (cont.) Polynomial accumulation:  We partition the bits of the key into a sequence of components of fixed length (e.g., 8, 16 or 32 bits) a 0 a 1 … a n-1  We evaluate the polynomial p(z) = a 0 + a 1 z + a 2 z 2 + … + a n-1 z n-1 at a fixed value z, ignoring overflows  Especially suitable for strings (e.g., the choice z = 33 gives < 6 collisions on a set of 50,000 English words) /** * Polynomial p(z) can be * evaluated in O(n) time by * Horner’s rule: **/ p  0; for (int i = n-1; i >= 0 ; i--) p  a i + z ∗ p; return p; /** * Polynomial p(z) can be * evaluated in O(n) time by * Horner’s rule: **/ p  0; for (int i = n-1; i >= 0 ; i--) p  a i + z ∗ p; return p; last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets20

Compression Functions Division:  h 2 (y) = y mod N  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 MAD: Multiply, Add & Divide:  h 2 (y) = (ay + b) mod N  a and b are nonnegative integers such that a mod N  0 Otherwise, every integer would map to the same value b last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets21

Abstract Hash Map in Java last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets22

Abstract Hash Map in Java, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets23

Collision Handling 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 – Separate chaining is simple, but requires additional memory outside the table last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets24   

Map with Separate Chaining Delegate operations to a list-based map at each cell: Algorithm get(k) return A[h(k)].get(k) Algorithm put(k,v) t  A[h(k)].put(k,v) if t = null then // k is a new key n  n + 1 return t Algorithm remove(k) t  A[h(k)].remove(k) if t ≠ null then // k was found n  n - 1 return t Delegate operations to a list-based map at each cell: Algorithm get(k) return A[h(k)].get(k) Algorithm put(k,v) t  A[h(k)].put(k,v) if t = null then // k is a new key n  n + 1 return t Algorithm remove(k) t  A[h(k)].remove(k) if t ≠ null then // k was found n  n - 1 return t last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets25

Hash Table with Chaining last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets26

Hash Table with Chaining, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets27

Open Addressing: Linear Probing 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 Each table cell inspected is referred to as a “probe” Colliding items lump together, causing future collisions to cause a longer sequence of probes Example: – h(x) = x mod 13 – Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in that order last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets

Search with Linear Probing Consider a hash table A that uses linear probing get(k) – We start at cell h(k) – We probe consecutive locations until one of the following occurs An item with key k is found, or An empty cell is found, or N cells have been unsuccessfully probed last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets29 Algorithm get(k) i  h(k) p  0 repeat c  A[i] if c =  return null else if c.getKey() = k return c.getValue() else i  (i + 1) mod N p  p + 1 until p = N return null Algorithm get(k) i  h(k) p  0 repeat c  A[i] if c =  return null else if c.getKey() = k return c.getValue() else i  (i + 1) mod N p  p + 1 until p = N return null

Updates with Linear Probing To handle insertions and deletions, we introduce a special object, called DEFUNCT, which replaces deleted elements remove(k)  search for an entry with key k  If such an entry (k, v) is found, replace it with the special item DEFUNCT and return element v Else, return null put(k, v)  throw an exception if the table is full  start at cell h(k)  probe consecutive cells until one of the following occurs  A cell i is found that is either empty or stores DEFUNCT, or  N cells have been unsuccessfully probed  store (k, v) in cell i last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets30

Probe Hash Map in Java last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets31

Probe Hash Map in Java, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets32

Probe Hash Map in Java, 3 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets33

Open Addressing: Double Hashing Double hashing uses a secondary hash function d(k) and handles collisions by placing an item in the first available cell of the series (i + jd(k)) mod N for j = 0, 1, …, N – 1 The secondary hash function d(k) cannot have zero values The table size N must be a prime to allow probing of all the cells Common choice of secondary hash function: d(k) = q - k mod q where – q < N – q is a prime possible values for d(k) are {1, 2, …, q} last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets34

Example of Double Hashing Consider a hash table storing integer keys that handles collision with double hashing – N = 13 – h(k) = k mod 13 – d(k) = 7 - k mod 7 Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in that order last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets

Performance of Hashing O(1) expected running time of all the dictionary operations In practice, hashing is very fast provided the load factor is not close to 100% Applications of hash tables: – small databases – compilers – browser caches last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets36

Summary last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets37 Hash tables Hash function = hash code + compression function Hash codes: – Java default memory address – Key integer cast – Component sum – Polynomial accumulation –... Collision handling: – Separate chaining – Open addressing: Linear probing Double hashing Performance of hashing – Worst-case – Expected case

Skip Lists  S0S0 S1S1 S2S2 S3S3    2315 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets38

What is a Skip List A skip list for a set S of distinct (key, value) items is a series of lists S 0, S 1, …, S h such that – Each list S i contains the special keys -  and +  – List S 0 contains the keys of S in non-decreasing order – Each list is a subsequence of the previous one, i.e., S 0  S 1  …  S h – List S h contains only the two special keys We show how to use a skip list to implement the map ADT last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets     31  64  3134  23 S0S0 S1S1 S2S2 S3S3

Search We search for a key x in a skip list as follows: – We start at the first position of the top list – At the current position p, we compare x with y  key(next(p)) x = y: we return element(next(p)) x > y: we “scan forward” x < y: we “drop down” – If we try to drop down past the bottom list, we return null Example: search for 78 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets40  S0S0 S1S1 S2S2 S3S3  31  64  3134    scan forward drop down

Randomized Algorithms A randomized algorithm performs coin tosses (i.e., uses random bits) to control its execution It contains statements of the type b  random() // b  {0, 1} if b = 0 do A … else // b = 1 do B … Its running time depends on the outcomes of the coin tosses We analyze the expected running time of a randomized algorithm under the following assumptions – coins are unbiased, and – 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 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets41

Insertion To insert an entry (k, v) into a skip list, we use a randomized algorithm: – We repeatedly toss a coin until we get tails, and we denote with i the number of times the coin came up heads – If i  h, we add to the skip list new lists S h+1, …, S i +1, each containing only the two special keys – We search for k in the skip list and find the positions p 0, p 1, …, p i of the items with largest key less than k in each list S 0, S 1, …, S i – For j  0.. i, we insert item (k, v) into list S j after position p j Example: insert key 15, with i = 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets42    23   S0S0 S1S1 S2S2  S0S0 S1S1 S2S2 S3S3    2315 p0p0 p1p1 p2p2

Deletion To remove an entry with key k from a skip list, we do: – We search for k in the skip list and find the positions p 0, p 1, …, p i of the items with key k, where position p j is in list S j – We remove positions p 0, p 1, …, p i from the lists S 0, S 1, …, S i – We remove all but one list containing only the two special keys Example: remove key 34 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets43  4512  23  S0S0 S1S1 S2S2  S0S0 S1S1 S2S2 S3S3     p0p0 p1p1 p2p2

Implementation We can implement a skip list with quad-nodes A quad-node stores: – entry – link to the node prev – link to the node next – link to the node below – link to the node above We also define special keys PLUS_INF and MINUS_INF, and we modify the key comparator to handle them last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets44 x quad-node

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 i consecutive heads when flipping a coin is 1/2 i Fact 2: If each of n entries is present in a set with probability p, the expected size of the set is np last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets45  the expected space usage of a skip list with n items is O(n)

Height The running time of the search an insertion algorithms is affected by the height h of the skip list We show that with high probability, a skip list with n items has height O(log n) We use the following additional probabilistic fact: Fact 3: If each of n events has probability p, the probability that at least one of those n events occurs is at most np Consider a skip list with n enteries – By Fact 1, we insert an entry in list S i with probability 1/2 i – By Fact 3, the probability that list S i has at least one item is at most n/2 i By picking i = 3log n, we have that the probability that S 3log n has at least one entry is at most n/2 3log n = n/n 3 = 1/n 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets46  the height of a skip list with n entries is at most 3log n with probability at least 1 - 1/n 2

Search and Update Times The search time in a skip list is proportional to – number of drop-down steps, plus – number of scan-forward steps drop-down steps are bounded by the height of the skip list and thus are O(log n) with high probability 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 O(log n) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets47  in a skip list, the expected time for a search, insert, or delete is O(log n).

Summary A skip list is a data structure for maps It uses a randomized insertion algorithm In a skip list with n entries: – expected space is O(n) – expected time for search, insert and delete is O(log n) Using a more complex probabilistic analysis, one can show that these performance bounds hold with high probability Skip lists are fast and simple to implement in practice last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets48

Sets, Multisets, & Multimaps last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets49

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 (aka, bag) is a set-like container that allows duplicates. A multimap 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. last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 50

Set ADT last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 51

Storing a Set in a List We can implement a set with a list Elements are stored sorted according to some canonical ordering The space used is O(n) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets52  List Nodes storing set elements in order Set elements

Generic Merging Generalized merge of two sorted lists A and B Template method genericMerge Auxiliary methods – aIsLess – bIsLess – bothAreEqual Runs in O(n A + n B ) time provided the auxiliary methods run in O(1) time last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets53 Algorithm genericMerge(A, B) S  empty sequence while  A.isEmpty()   B.isEmpty() a  A.first().element(); b  B.first().element() if a < b aIsLess(a, S); A.remove(A.first()) else if b < a bIsLess(b, S); B.remove(B.first()) else // b = a bothAreEqual(a, b, S) A.remove(A.first()); B.remove(B.first()) while  A.isEmpty() aIsLess(a, S); A.remove(A.first()) while  B.isEmpty() bIsLess(b, S); B.remove(B.first()) return S Algorithm genericMerge(A, B) S  empty sequence while  A.isEmpty()   B.isEmpty() a  A.first().element(); b  B.first().element() if a < b aIsLess(a, S); A.remove(A.first()) else if b < a bIsLess(b, S); B.remove(B.first()) else // b = a bothAreEqual(a, b, S) A.remove(A.first()); B.remove(B.first()) while  A.isEmpty() aIsLess(a, S); A.remove(A.first()) while  B.isEmpty() bIsLess(b, S); B.remove(B.first()) return S

Using Generic Merge for Set Operations Any of the set operations can be implemented using a generic merge For example: intersection: only copy elements that are duplicated in both lists union: copy every element from both lists except for the duplicates All methods run in linear time last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets54

Multimap A multimap is similar to a map, except that it can store multiple entries with the same key We can implement a multimap M by means of a map M’ – For every key k in M, let E(k) be the list of entries of M with key k – The entries of M’ are the pairs (k, E(k)) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets55

Mulitmaps last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets56

Java Implementation last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets57

Java Implementation, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets58

Java Implementation, 3 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets59

Summary Sets, multisets, and multimaps Implementation – linked list – hash table – skip list Generic merge Set operations using generic merge last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 60

last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 61