{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Practice 3: Data Structures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Difficulty assessment:\n",
"\n",
"(\\*) Basic. You should be able to easily do this.\n",
"\n",
"(\\*\\*) Standard. Core material to test your understanding.\n",
"\n",
"(\\*\\*\\*) Advanced. Possibly slightly above the level of the assignments."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Hash tables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 1 ( \\*\\* ):**\n",
" \n",
"(a) You have a universe of 30 numbers $\\{0, 1, \\ldots, 29\\}$ and a hash-table of size $10$. Which hash-function is better, $h_1(k) = k \\mod 10$, or $h_2(k) = \\lfloor k/10\\rfloor$?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** The first hash-function selects the last digit of a number as a hash value, and\n",
"the second hash function the first. The first hash function is better because its image covers the whole hash-table, whereas the image of the second hash function, $\\{0, 1, 2\\}$, is only a subset of\n",
"the hash-table. Moreover, the first hash-function distributes the hash-values evenly over\n",
"the hash table, thus if the keys drawn from the universe are random, there will be few\n",
"collisions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(b) How many different hash functions exist that map from a universe of size $n$ to the\n",
"integers $1$ to $m$?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** The number of functions that map from a universe of size $n$ to the integers\n",
"$1\\ldots m$ is $m^n$, as each of the $n$ elements can map to one of $m$ integers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 2 ( \\*\\* ):**\n",
" \n",
"(a) Draw the hash table of length $m = 16$ resulting from hashing the keys $8, 12, 40, 13, 88,\n",
"45, 29, 20, 23$, and $77$, using the hash function $h(k) = (3k + 1) \\mod 16$ and assuming\n",
"collisions are handled by chaining. Is $m = 16$ a good choice for the size of a table? Why\n",
"or why not?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** The following image illustrates the keys inserted into a hash-table of size 16:\n",
"\n",
"\n",
"\n",
"For the given hash function, $m = 16$ is a bad choice for the size of a hash table because\n",
"it is a power of $2$. When we are using the division method to create a hash function, if\n",
"the size of the table $m = 2^p$, then the hash values will only depend on the lower $p$ bits.\n",
"This may lead to more collisions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(b) Repeat the previous exercise for a table of size $m = 13$ using the hash function $h(k) =\n",
"(3k + 1) \\mod 13$. Why is $m = 13$ a better choice for the size of a hash table than\n",
"$m = 16$?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** The following image illustrates the keys inserted into a hash-table of size $13$:\n",
"\n",
"\n",
"\n",
"$m = 13$ is a better choice for a size of a hash table when using the division method to\n",
"create a hash function because it is prime and it is far enough from a power of two. A\n",
"hash function created by using the division method will not only depend on the lower\n",
"bits of the keys."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(c) What is the result of the previous exercise, assuming collisions are handled by linear\n",
"probing? Report for every key how often you had to probe unsuccessfully before you could insert the key, and report the total number of unsuccessful probes."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** \n",
"\n",
"\n",
"\n",
"For keys $\\{8, 12, 40, 13, 88, 45, 29, 20\\}$ there were $0$ unsuccessful probes. For keys $23$ and $77$ there were $2$ unsuccessful probes. The total number of unsuccessful probes is $4$."
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"(d) What is the result of (c) assuming collisions are handled by double hashing with a\n",
"primary hash function $h'(k) = h(k)$ and a secondary hash function $h''(k) = k \\mod 15$?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** \n",
"\n",
"\n",
"\n",
"For keys $\\{8, 12, 40, 13, 88, 45, 29, 20\\}$ there were $0$ unsuccessful probes. For key $23$ there was $1$ unsuccessful probe, and for key $77$ there were $2$ unsuccessful probes. The total number of unsuccessful probes is 3."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 3:**\n",
"Describe algorithms for Hash-Chain-Insert, Hash-Chain-Delete, and Hash-Chain-Search for a hash table with chaining, where the (doubly-linked) lists are stored in a sorted order. Analyze the running time of the algorithms."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:** \n",
"\n",
"(i) Hash-Chain-Insert: instead of inserting $x$ at the head of $T[h(x:key)]$ we need to\n",
"find the proper position of $x$ in the list. So, we compare the elements of $T[h(x:key)]$\n",
"one by one with $x$ until we reach the end of the list or until we find an element $y$\n",
"such that $y:key > x:key$. Then, we insert $x$ in front of $y$, or at the end of the list if\n",
"no such $y$ was found.\n",
"\n",
"*Running time analysis:* The worst-case running time of Hash-Chain-Insert is\n",
"$\\Theta(n)$ (if all the elements hash into the same slot, and $x$ is the maximum element,\n",
"then the whole list needs to be traversed until we can insert $x$. On average, if the\n",
"load factor of the hash table is $\\alpha$, the running time of Hash-Chain-Insert will be\n",
"$\\Theta(1 + \\alpha)$.\n",
"\n",
"(ii) Hash-Chain-Search: search for an element with key $k$ in the list $T[h(k)]$. We can use\n",
"the same algorithm as for the non-sorted lists. We can slightly improve the algorithm by stopping the search when we find a $y$ with $y:key > x:key$. The running time for both variants is $\\Theta(1 + \\alpha)$.\n",
"\n",
"(iii) Hash-Chain-Delete: delete element $x$ from the list $T[h(x:key)]$. The algorithm\n",
"is the same as for the non-sorted lists: when deleting $x$ from a sorted list, the sorted\n",
"order of the remaining elements is preserved. The running time is $O(1)$ if the lists\n",
"are doubly linked."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 4:** Consider two sets of integers, $S = \\{s_1, s_2, \\ldots, s_m\\}$ and $T = \\{t_1, t_2, \\ldots, t_n\\}$, $m \\leq n$. Describe an algorithm that uses a hash table of size $m$ to test whether $S$ is a subset of $T$, that runs in $O(n)$ time. You may assume the existence of a suitable hash function that satisifies the assumption of simple uniform hashing."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Solution:**\n",
" \n",
"Let $H$ be the hash table of size $m$ and $h()$ be a corresponding uniform hash\n",
"function. The algorithm is the following: First, insert all the elements of $T$ into $H$. Next,\n",
"for each element $s_i$ in $S$ search for $s_i$ in $H$. If for some $s_i$ the search was unsuccessful (i.e. returns None), then $s_i \\not \\in T$, and thus $S \\not \\subset T$. Otherwise, report that $S \\subset T$.\n",
"\n",
"*Note: You could, but don't need to, add Python code here to clarify the algorithm.* Python code for this algorithm is given below.\n",
"\n",
"*Correctness:*\n",
"If $S \\subset T$, then for all elements of $S$ the search will return the corresponding\n",
"element of $T$ from the hash table. Therefore all searches are successful, and the algorithm will correctly report that $S \\subset T$.\n",
"\n",
"If $S \\not \\subset T$, then there will be an element $s_i$ from $S$ such that $s_i \\not \\in T$. Then, searching for $s_i$ in the hash table will return None, and the algorithm correctly reports that $S \\not \\subset T$.\n",
"\n",
"*Running Time:*\n",
"Inserting $n$ elements into the a hashtable takes (with chaining) takes $O(1)\\cdot n = O(n)$ time. Searching takes $O(1+\\alpha)$ time per element, where $\\alpha$ is the load factor, and $\\alpha = n/m$. Thus, searching for $m$ elements takes $m O(1+n/m) = O(m + n)$ time. Overall the algorithm runs in $O(m + n)$ time."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Solution code:\n",
"# A simplistic hash table for the purpose of this exercise. It just uses keys (instead of elements with keys)\n",
"class HashTableChaining:\n",
" hashTable = []\n",
" size = 0\n",
" \n",
" def __init__(self, size):\n",
" self.size = size\n",
" self.hashTable = [[]]*size\n",
" \n",
" def h(self,key):\n",
" # division method. Note that depending on the table size, this might be not a good hash function, but it serves as an example here.\n",
" return key%self.size \n",
" \n",
" def insert(self, key):\n",
" self.hashTable[self.h(key)].append(key)\n",
" \n",
" def search(self,key): \n",
" # Since there are no elements, this search routine will simply return the key if it finds it, and None otherwise \n",
" if key in self.hashTable[self.h(key)]: return key\n",
" else: return None\n",
" \n",
"def isSubset (S,T):\n",
" m = len(S)\n",
" n = len(T)\n",
" H = HashTableChaining(m)\n",
" for t in T: H.insert(t)\n",
" for s in S:\n",
" if not H.search(s): return False\n",
" return True\n",
"\n",
"isSubset([1,2,3],[1,4,2,3])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}