Maps, Hash Tables, Skip Lists, Sets last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 1 Maps & Dictionaries last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 2 Maps • 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). last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 3 The Map ADT get(k): put(k, v): remove(k): entrySet(): keySet(): values(): size() isEmpty() last Update: Nov 4, 2014 if the map M has an entry with key k, return its associated value; else, return null 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 if the map M has an entry with key k, remove it from M and return its associated value; else, return null return an iterable collection of the entries in M return an iterable collection of the keys in M return an iterator of the values in M EECS2011: Maps, Hash Tables, Skip Lists, Sets 4 Example Operation Output Map isEmpty() put(5,A) put(7,B) put(2,C) put(8,D) true null null null null Ø (5,A) (5,A),(7,B) (5,A),(7,B),(2,C) (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) remove(2) get(2) isEmpty() A E null false (7,B),(2,E),(8,D) (7,B),(8,D) (7,B),(8,D) (7,B),(8,D) last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 5 The Java Map Hierarchy «interface» Map (§ 10.1.1) «interface» SortedMap (§ 10.3) AbstractMap (§ 10.1.3) AbstractSortedMap (§ 10.3) UnsortedTableMap (§ 10.1.4) AbstractHashMap (§ 10.2.4) ChainHashMap (§10.2.4) last Update: Nov 4, 2014 SortedTableMap (§ 10.3.1) ProbeHashMap (§ 10.2.4) EECS2011: Maps, Hash Tables, Skip Lists, Sets TreeMap (chapter 11) (additional subclasses) 6 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 nodes/positions header 9 c 6 c 5 c trailer 8 c entries last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 7 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() = k then 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)) nn+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) nn–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 0 1 2 3 4 last Update: Nov 4, 2014 025-612-0001 981-101-0002 451-229-0004 EECS2011: Maps, Hash Tables, Skip Lists, Sets 12 Recall the Map ADT get(k): put(k, v): remove(k): entrySet(): keySet(): values(): size() isEmpty() last Update: Nov 4, 2014 if the map M has an entry with key k, return its associated value; else, return null 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 if the map M has an entry with key k, remove it from M and return its associated value; else, return null return an iterable collection of the entries in M return an iterable collection of the keys in M return an iterator of the values in M EECS2011: Maps, Hash Tables, Skip Lists, Sets 13 Intuitive Notion of a Map • 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. last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 14 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. 0 1 2 3 4 025-612-0001 981-101-0002 451-229-0004 … 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 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, Sets 16 Example last Update: Nov 4, 2014 025-612-0001 981-101-0002 451-229-0004 … • We design a hash table for a map 0 1 storing entries as 2 (key, value) (SIN, Name), 3 where SIN (social insurance number) 4 is a ten-digit positive integer • Our hash table uses an array of size N = 10,000 and the hash function 9997 9998 h(k) = last four digits of k 9999 200-751-9998 EECS2011: Maps, Hash Tables, Skip Lists, Sets 17 Hash Functions • The hash code is applied • A hash function is usually first, and the compression composed of two functions: Hash code: h1: keys integers Compression function: h2: integers [0, N - 1] last Update: Nov 4, 2014 function is applied next on the result, i.e., h(x) = h2(h1(x)) • The goal of the hash function is to “disperse” the keys in an apparently random way EECS2011: Maps, Hash Tables, Skip Lists, Sets 18 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) last Update: Nov 4, 2014 • 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) EECS2011: Maps, Hash Tables, Skip Lists, Sets 19 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) a0 a1 … an-1 We evaluate the polynomial p(z) = a0 + a1 z + a2 z2 + … + an-1zn-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) last Update: Nov 4, 2014 /** * 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 ai + z∗p; return p; EECS2011: Maps, Hash Tables, Skip Lists, Sets 20 Compression Functions • Division: • MAD: Multiply, Add & Divide: h2 (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 last Update: Nov 4, 2014 h2 (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 EECS2011: Maps, Hash Tables, Skip Lists, Sets 21 Abstract Hash Map in Java last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 22 Abstract Hash Map in Java, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 23 Collision Handling • Collisions occur when different elements are mapped to the same cell 0 1 2 3 4 025-612-0001 451-229-0004 981-101-0004 • 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, Sets 24 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 nn+1 return t Algorithm remove(k) t A[h(k)].remove(k) if t ≠ null then // k was found nn-1 return t last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 25 Hash Table with Chaining last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 26 Hash Table with Chaining, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 27 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 last Update: Nov 4, 2014 • Example: – h(x) = x mod 13 – Insert keys 18, 41, 22, 44, 59, 32, 31, 73, in that order 41 18 44 59 32 22 31 73 0 1 2 3 4 5 6 7 8 9 10 11 12 EECS2011: Maps, Hash Tables, Skip Lists, Sets 28 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 Algorithm get(k) i h(k) p0 repeat c A[i] if c = return null else if c.getKey() = k return c.getValue() else i (i + 1) mod N pp+1 until p = N return null EECS2011: Maps, Hash Tables, Skip Lists, Sets 29 Updates with Linear Probing • put(k, v) • To handle insertions and deletions, we introduce a special throw an exception if the object, called DEFUNCT, which table is full replaces deleted elements start at cell h(k) • remove(k) probe consecutive cells search for an entry with key k until one of the following If such an entry (k, v) is found, occurs replace it with the special item DEFUNCT and return element v Else, return null 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, Sets 30 Probe Hash Map in Java last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 31 Probe Hash Map in Java, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 32 Probe Hash Map in Java, 3 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 33 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 last Update: Nov 4, 2014 • 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} EECS2011: Maps, Hash Tables, Skip Lists, Sets 34 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 k 18 41 22 44 59 32 31 73 h (k ) d (k ) Probes 5 2 9 5 7 6 5 8 3 1 6 5 4 3 4 4 5 2 9 5 7 6 5 8 10 9 0 31 41 18 32 59 73 22 44 0 1 2 3 4 5 6 7 8 9 10 11 12 EECS2011: Maps, Hash Tables, Skip Lists, Sets 35 Performance of Hashing • O(n) worst case running time for search, insert, and remove e.g., when all inserted keys collide • The load factor 𝑎 = 𝑛/𝑁 affects the performance • With open addressing, assuming the hash values are random: expected number of probes 1 𝑗−1 = 𝑗𝑎 1−𝑎 = . 1−𝑎 • 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 𝑗≥1 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 36 Summary • Hash tables • Hash function = hash code + compression function • Hash codes: • Collision handling: – Separate chaining – Open addressing: • Linear probing • Double hashing – Java default memory address • Performance of hashing – Key integer cast – Worst-case – Component sum – Expected case – Polynomial accumulation – ... last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 37 Skip Lists S3 - S2 - 15 S1 - 15 23 15 23 S0 - last Update: Nov 4, 2014 + 10 + + 36 + EECS2011: Maps, Hash Tables, Skip Lists, Sets 38 What is a Skip List • A skip list for a set S of distinct (key, value) items is a series of lists S0, S1 , … , Sh such that – Each list Si contains the special keys - and + – List S0 contains the keys of S in non-decreasing order – Each list is a subsequence of the previous one, i.e., S0 S1 … Sh – List Sh contains only the two special keys • We show how to use a skip list to implement the map ADT S3 - S2 - S1 - S0 - + + 31 23 12 last Update: Nov 4, 2014 23 26 31 34 31 34 + 64 44 56 EECS2011: Maps, Hash Tables, Skip Lists, Sets 64 78 + 39 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 S3 - S2 - S1 - S0 - + scan forward + 31 drop down 23 12 last Update: Nov 4, 2014 23 26 31 34 31 34 + 64 44 56 EECS2011: Maps, Hash Tables, Skip Lists, Sets 64 78 + 40 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() if b = 0 do A … else // b = 1 do B … // b {0, 1} • 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”) • Its running time depends on the outcomes of the coin tosses last Update: Nov 4, 2014 • We analyze the expected running time of a randomized algorithm under the following assumptions – coins are unbiased, and – coin tosses are independent • We use a randomized algorithm to insert items into a skip list EECS2011: Maps, Hash Tables, Skip Lists, Sets 41 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 Sh+1, … , Si +1, each containing only the two special keys – We search for k in the skip list and find the positions p0, p1 , …, pi of the items with largest key less than k in each list S0, S1, … , Si – For j 0 .. i, we insert item (k, v) into list Sj after position pj Example: insert key 15, with i = 2 p2 S2 - p1 S1 - S0 - S3 - 23 p0 10 last Update: Nov 4, 2014 23 36 + + S2 - 15 + S1 - 15 23 + S0 - 15 23 10 EECS2011: Maps, Hash Tables, Skip Lists, Sets + + 36 + 42 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 p0, p1 , …, pi of the items with key k, where position pj is in list Sj – We remove positions p0, p1 , …, pi from the lists S0, S1, … , Si – We remove all but one list containing only the two special keys Example: remove key 34 S3 - + p2 S2 - 34 p1 S1 - S0 - 23 34 p0 12 last Update: Nov 4, 2014 23 34 45 + S2 - + S1 - + S0 - EECS2011: Maps, Hash Tables, Skip Lists, Sets + + 23 12 23 45 + 43 Implementation • We can implement a skip list with quad-nodes • A quad-node stores: – – – – – quad-node entry link to the node prev link to the node next link to the node below link to the node above x • 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, Sets 44 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/2i 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 • Consider a skip list with n entries – By Fact 1, we insert an entry in list Si with probability 1/2i – By Fact 2, the expected size of list Si is n/2i • The expected number of nodes used by the skip list is ℎ 𝑖=0 𝑛 = 𝑛 2𝑖 ℎ 𝑖=0 1 < 2𝑛 2𝑖 the expected space usage of a skip list with n items is O(n) EECS2011: Maps, Hash Tables, Skip Lists, Sets 45 Height • The running time of the search an • Consider a skip list with n enteries insertion algorithms is affected by – By Fact 1, we insert an entry in list Si with probability 1/2i the height h of the skip list – By Fact 3, the probability that list Si • We show that with high probability, has at least one item is at most n/2i a skip list with n items has height O(log n) • By picking i = 3log n, we have that the probability that S3log n has at • We use the following additional least one entry is at most 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 last Update: Nov 4, 2014 n/23log n = n/n3 = 1/n2 the height of a skip list with n entries is at most 3log n with probability at least 1 - 1/n2 EECS2011: Maps, Hash Tables, Skip Lists, Sets 46 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 last Update: Nov 4, 2014 • 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 scanforward steps is O(log n) in a skip list, the expected time for a search, insert, or delete is O(log n). EECS2011: Maps, Hash Tables, Skip Lists, Sets 47 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, Sets 48 Sets, Multisets, & Multimaps last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 49 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) Nodes storing set elements in order List Set elements last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 52 Generic Merging Algorithm genericMerge(A, B) • Generalized merge of S empty sequence two sorted lists A and B while A.isEmpty() B.isEmpty() • Template method a A.first().element(); b B.first().element() genericMerge if a < b • Auxiliary methods aIsLess(a, S); A.remove(A.first()) – aIsLess – bIsLess – bothAreEqual • Runs in O(nA + nB) time provided the auxiliary methods run in O(1) time last Update: Nov 4, 2014 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 EECS2011: Maps, Hash Tables, Skip Lists, Sets 53 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, Sets 54 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, Sets 55 Mulitmaps last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 56 Java Implementation last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 57 Java Implementation, 2 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 58 Java Implementation, 3 last Update: Nov 4, 2014 EECS2011: Maps, Hash Tables, Skip Lists, Sets 59 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