Data Structures and Data Management

Chapter 1 - Introduction

Common facts we will use:

Arithmetic sequence: ∑i=0n−1(a+di)=na+dn(n−1)2∈Θ(n2)\sum_{i=0}^{n-1}(a+di) = na + \frac{dn(n-1)}{2} \in \Theta (n^2) if d≠0d \neq 0 - we will especially use ∑i=0n−1i=n(n−1)2∈Θ(n2)\sum_{i=0}^{n-1}i = \frac{n(n-1)}{2} \in \Theta (n^2) Geometric sequence: ∑i=0n−1ari=\sum_{i=0}^{n-1}ar^i =

Harmonic sequence: Hn:=∑i=1n1i=ln(n)+γ+o(1)∈Θ(logn)H_n := \sum_{i=1}^{n} \frac{1}{i} = ln(n) + \gamma + o(1) \in \Theta (log n)

Logarithms:

Factorial:

Probability and moments:

1.2 - Definitions and Assumptions

Problems

Formal definition of problem in computer science is: it is a language i.e., a (possibly infinite) subset of words of an alphabet, and we want to know whether a given word belonds to the language. In this course we don't need this definition and instead we say a problem consists of a description of all possible inputs ("instances") and a requirement on the desired output.
The course focuses on two problems:

Algorithms

Precise definition of algorithm is that it is a Turing machine.
Our definition: an algorithm is a step-by-step process that caries out a series of computations on the given input.

Computer model

We are using the Random Acecss Machine (RAM) model:

Algorithm analysis

Run-time of an algorithm is the number of memory accesses plus the number of primitive operations.

The size of an input (instance) II is the number of memory cells it takes.

We consider the worst case to calculate the run-time (gives a guaranteed upper bound).

1.3 - Asymptotic Notation

Definition 1: Let f(n),g(n)f(n), g(n) be two functions. We say that f(n)∈O(g(n))f(n) \in O(g(n)) if there exists c>0c > 0 and n0≥0n_0 \geq 0 such that ∣f(n)∣≤c∣g(n)∣|f(n)| \leq c|g(n)| for all n≥n0n \geq n_0.

The absolute value signs can usually be ignored in this course as we're dealing with large positive integers.

Tight asymptotic bounds

Regular big O allows too much freedome (some function in O(n2)O(n^2) is also in O(n100)O(n^100))

We want to say "the run-time is quadratic and we can't get any better than that"

Definition 2: Let f(n),g(n)f(n), g(n) be two functions. We say f(n)∈Ω(g(n))f(n) \in \Omega (g(n)) if there exists c>0c > 0 and n0≥0n_0 \geq 0 such that ∣f(n)≥c∣g(n)∣|f(n) \geq c|g(n)| for all n≥n0n \geq n_0

Definition 3: Let f(n),g(n)f(n), g(n) be two functions. We say f(n)∈Θ(g(n))f(n) \in \Theta (g(n)) if f(n)∈O(g(n))f(n) \in O(g(n)) and f(n)∈Ω(g(n))f(n) \in \Omega(g(n)). So there exist constants n0≥0n_0 \geq 0 and c1,c2>0c_1, c_2 > 0 such that c1∣g(n)∣≤∣f(n)∣≤c2∣g(n)∣c_1|g(n)| \leq |f(n)| \leq c_2|g(n)| for all n≥n0n \geq n_0

Growth rates

T(n)T(n) is the run-time of some algorithm. Cmmon growth rates have names:

Friends of OO and Ω\Omega

Definition 4: Let f(n),g(n)f(n), g(n) be two functions. We say that f(n)∈o(g(n))f(n) \in o(g(n)) if for any constant c>0c > 0 there exists an n0≥0n_0 \geq 0 such that ∣f(n)≤c∣g(n)∣|f(n) \leq c|g(n)| for all n≥n0n \geq n_0
We say that f(n)∈ω(g(n))f(n) \in \omega (g(n)) if for any constant c>0c > 0 there exists an n0≥0n_0 \geq 0 such that ∣f(n)∣≥c∣g(n)∣|f(n)| \geq c|g(n)| for all n≥n0n \geq n_0.

We rarely use little-omega in this course but we use little-o to state impossibilities and to express lower order terms if we care about constant "number of comparisons is 2n+o(n)2n + o(n)"

With big-O you hold (you get to choose one) one constant cc and show that there exists n0n_0. For little-o you must show for any c (particularly any small c) there exists n0n_0

Usually we do not prove from first principle (definition) little-o and little-omega propositions (we use limits).

Rules for asymptotic notation

Some basic rules (for non-negative functions)

Identity: f(n)∈Θ(f(n))f(n) \in \Theta(f(n))

Constant multiplication: K⋅f(n)∈Θ(f(n))K \cdot f(n) \in \Theta(f(n))

Transitivity: If f(n)∈O(g(n))f(n) \in O(g(n)) and g(n)∈O(h(n))g(n) \in O(h(n)) then f(n)∈O(h(n))f(n) \in O(h(n)) the same holds for Ω\Omega This implies Dominance: - If f(n)f(n) in O(g(n))O(g(n)), and g(n)≤h(n)g(n) \leq h(n) for all sufficiently large n, then f(n)∈O(h(n))f(n) \in O(h(n)) - the same holds for Ω\Omega but g(n)≥h(n)g(n) \geq h(n) for sufficiently large n

Addition: If f(n)∈O(g(n))f(n) \in O(g(n)) and f′(n)∈O(g′(n))f'(n) \in O(g'(n)) then f(n)+f′(n)∈\O(g(n)+g′(n))f(n)+f'(n) \in \O(g(n) + g'(n))

Maximum-rule for OO: If a function h(n)h(n) belongs to O(f(n)+g(n))O(f(n) + g(n)) then it belongs to O(max{f(n),g(n)})O(max\{f(n), g(n)\}). Here max{f(n),g(n)}max\{f(n), g(n)\} denotes the function that takes the pointwise maximum, i.e., for every nn it takes on whichever value of f(n)f(n) and g(n)g(n) is the bigger one.

Maximum-rule for OO: If a function h(n)h(n) belongs to Ω(f(n)+g(n))\Omega(f(n) + g(n)) then it belongs to Ω(max{f(n),g(n)})\Omega(max\{f(n),g(n)\})

Warning about arithmetic Big-O notation refers to sets do not perform arithmetic on sets.
We say O(n)⊂O(n2)O(n) \subset O(n^2) not O(n)<O(n2)O(n) < O(n^2)

Lemma 1.1: Let f(n), g(n) be two functions that satisfy f(n),g(n)>0f(n), g(n) > 0 for sufficiently large n$ assume that the limit limn→∞f(n)g(n)lim_{n \rightarrow \infty} \frac{f(n)}{g(n)} exists and call it LL. Then ,
f(n)∈f(n) \in

Lemma 1.2: let f(n), g(n) be two functions that satisfy f(n),g(n)>0f(n), g(n) > 0 for sufficiently large n. Then f(n)∈o(g(n))f(n) \in o(g(n)) if and only if limn→∞f(n)g(n)lim_{n \rightarrow \infty} \frac{f(n)}{g(n)} exists and equals 0.

Polynomial rule: If ff is a polynomial with leading term cd⋅ndc_d \cdot n ^ d then f(n)∈Θ(nd)f(n) \in \Theta (n^d)

Logarithm rule:

Relationships between asymptotic notations: A

Lemma 1.4: Let f(n),g(n)f(n), g(n) be two functions with f(n),g(n)>0f(n),g(n) > 0 for sufficiently large n. If f(n)∈Ω(g(n))f(n) \in \Omega(g(n)) then f(n)∉o(g(n))f(n) \notin o(g(n))

1.4 - Algorithm analysis revisted

How do we describe an algorithm?

Step 1. Describe the algorithm idea

Should be in natural words with 1-2 sentences and/or a picture that describes the important insights.

For example (insertion-sort): Keep a sorted part, and repeatedly insert one more item into its correct place in it.

Step 2. Give a detailed description

This typically means pseudo-code. Should be descriptive enough than an experienced programmer can convert to code without much thinking.

// Algorithm 1.4: insertion-sort(A, n <- A.size) Input : Array A of size at least n for i <- 1 to n-1 do j <- i while j > 0 and A[j] > A[j-1] do swap A[j] and A[j-1] j <- j - 1

Step 3. Argue correctness

loop-invariants, and stuff from cs245. Proofs for this course don't need to be as formal as cs245.

Step 4. Analyze the efficiency

Usually the worst-case scenario, but if average is better than worst case this should be stated. Both should be using Θ\Theta-notation (tight bounds).

Comparing algorithms

We consider one algorithm to be worse if its run-time is asymptotically strictly smaller (little-o).

Case study: Merge-sort

Step 1: The idea is to split input into roughly two halves and sort them recursively then merge the two sorted parts together.

Step 2: Pseudo-code

Algorithm 1.5: merge-sort(A, n = A.size(), l = 0, r = n-1, s = NIL)

Input : Array a of size at least n, 0<=l<=r<=n-1 (possibly uninitialized) array S of size n if S is NIL then initialize it as array S[0..n-1] if (r <= l) then return else m = floor((r + l) / 2) merge-sort(A,n,l,m,S) merge-srot(A,n,m+1, r, S) merge(A, l, m, r, S)

Algorithm 1.5: merge(A, l, m, r, S)

Input : A[0..n-1] is an array, A[l..m] is sorted, A[m+1..r] is sorted. S[0..n-1] is an array copy A[l..r] into S[l..r] int il = l int ir = m + 1 for (k = l; k <= r; k++) do if il > m then A[k] = S[ir++] else if ir > r then A[k] = S[il++] else if S[il] <= S[ir] then A[k] = S[il++] else A[k] = S[ir++]

Step 3: Correctness. First argue that merge achieves a sorted array afterwards. This

We should also brieful discuss that the recursion terminates. Show that the two subarray are smaller and we reach r>=l eventually.

Step 4: Analyze the efficiency

Since merge-sort is recursive we have a recursive definition for the worst-case T(n)≈2T(n/2)+cnT(n) \approx 2T(n/2) + cn (and c if <=1). Sincethe growth of most algorithms is smooth relative to n we just assume that n is divisible as needed (don't worry about n/2).

There is a table for finding Θ\Theta for recursive expressions.

We should also discuss space

1.5 - Take-home messages

Algorithm merge-sort solves the sorting problem in Θ(nlog(n))\Theta(n log(n)) run-time and uses Θ(n)\Theta(n) auxiliary space.

Module 2

Stack ADT

LIFO (last-in first-out)

Extra operations:

We can implement this with an array or a linked-list

Queue ADT

FIFO (first-in first-out)

circular array

Priority Queue

An ADT consisting of items each with a priority

main operations

deleteMax is also called

Above we describe maximum-oriented priority queue, but it could be replaced with a minimum-oriented priority queue

Using a priority queue to sort

PQ-Sort(A[0..n-1]) initialize PQ to an empty priority queue for k = 0 to n - 1 do PQ.insert(A[k], A[k]) for k = n - 1 down to 0 do A[k] = PQ.deleteMax()

note: we usually assyme dynamic arrays i.e, expanding by doubling and so ammortized over all insertions this takes O(1)O(1) extra time

Suppose we start from an array A of length 1, we can do n insertions n=2kn = 2^k

Realization 1: unsorted arrays

Using unsorted arrays

Realization 2: sorted arrays

PQ-sort with sorted arrays is insertion sort, the runtime is O(n2)O(n^2)

Binary Heaps

A (binary) heap is a certain type of binary tree

A binary tree is either

Terminology: root, leaf, parent, child, level, sibling, ancestor, descendant

Any binary tree with n nodes has a height at least

log(n+1)−1∈Ω(logn)log(n+1) - 1 \in \Omega (log n)

A heap is a binary tree with the following two properties:

The full name for this is a max-oriented binary heap.

Lemma: The height of a heap is Θ(log(n))\Theta (log (n))

Heap implementation:

Heaps should not be stored as binary trees.

We can store a heap in an array because of its structure property.

we wrap these operations in root(), parent(i), last(n)

Insert in Heaps

fix-up(A,k) k: an index corresponding to a node of the heap while parent(k) exists and A[parent(k)] < A[k] do swap A[k] and A[parent(k)] k = parent(k)

deleteMax in Heaps

fix-down(A, n, k): A: an array that stores a heap of size n k: an index corresponding to a node of the heap while k is not a leaf do // find the child with the larger key j = left child of k if (j is not last(n) and A[j+1] > A[j]) j = j + 1 if A[k] >= A[j] break swap A[j] and A[k] k = j

Priority queue using heaps

insert(x) increase size l = last(size) A[l] = x fix-up(A, l) deleteMax() l = last(size) swap A[root()] and A[l] decrease size fix-down(A, size, root()) return A[l]

Time: O( height of tree)=O(log(n))O(\textrm{ height of tree}) = O(log(n))

Sorting using heaps

PQsortWithHeaps(A) initialize H to an empty heap for k = 0 to n - 1 do H.insert(A[k]) (we just insert keys, no items) for k = n - 1 down to 0 do A[k] = H.deleteMax()

Can improve this with two simple tricks -> Heapsort

  1. Heaps can be built faster if we know all input in advance
  2. Can use the same array for input and heap -> O(1)O(1)$ auxiliary space

Building heaps with fix-up

Problem: given n items all at once build a heap containing them

Solution 1: start with empty heap and insert items one at a time

simpleHeapBuilding(A) A: an array initialize H as an empty heap for i = 0 to size(A) - 1 do H.insert(A[i])

This corresponds to doing fix-ups
Worst-case running time: Θ(n⋅log(n))\Theta (n \cdot log(n))

Solution 2: using fix-doesn instead:

heapify(A) A: an array n = A.size() for i = 0 parent(last(n)) downto 0 do fix-down(A, n, i)

HeapSort

HeapSort(A, n) //heapify n = A.size() for i = parent(last(n)) downto 0 do fix-down(A, n, i) // repeatedly find minimum while n > 1 // delete maximum swap items at A[root()] and A[last(n)] decrease n fix-down(A, n, root())

Module 2 Summary

Find the smallest item

Problem: Find the kth smallest item in array A of n distinct numbers

Solution 1: Make k passes through the array, deleting the minimum number each time

Solution 2: Sort A, then return A[k-1]

Solution 3: Scan the array and maintain the k smallest numbers seen so far in a max-heap

Solution 4: Create a min-heap with heapify(A). Call deleteMin(A) k times

Module 4 - AVL Trees

Dictionary: ADT consisting of a collection of items each of which contains a

operations:

Examples: symbol table, license plate databse

Elementary Implementations

Unordered array or linked list

Ordered array

Binary Search Trees (review)

Structure:

Ordering:

BST as a realization of ADT Dictionary

BST::search(k)

BST::delete(x)

AVL Trees

AVL Tree : a BST with extra property

Rephrase: If node v has subtree L and R

Need to store the height of each subtree at every node

Height of an AVL Tree

Theorem: An AVL tree on n nodes has O(log n) height

AVL::insert(k, v)

AVL::insert(k, v) z = BST::insert(k, v) // leaf where k is now stored while (z is not NULL) if (|z.left.height - z.right.height| > 1) then let y be taller child of z let x be taller child of y z = restructure(x, y, z) // see later break // can argue that we are done (at max we fix one node in insert) setHeightFromSubtrees(z) z = z.parent setHeightFromSubtrees(u) u.height = 1 + max(u.left.height, u.right.height)

Rotations:

rotate-right(z) y = z.left, z.left = y.right, y.right = z setHeightFromSubtrees(z), setHeightFromSubtrees(y) return y // returns new root of subtree
restructure(x, y, z) node x has parent y and grandparent z case //right rotation z left- y left- x return rotate-right(z) // double-right rotation z left- y right-x z.left = rotate-left(y) return rotate-right(z) // double-left rotation z right- y left x z.right = rotate-right(y) return rotate-left(z) // left rotation z right- y right- x return rotate-left
AVL::delete(k) z = BST::delete(k) // assume z is parent of the BST node that was removed while (z is not null) if (|z.left.height - z.right.height| > 1) then let y be taller child of z let x be taller child of y z = restructure(x, y, z) // always continue up the path and fix if needed setHeightFromSubtrees(z) z = z.parent

Module 5 - Dictionary Implementations Not Based on BST

Realizations

Skip Lists

Motivation:

We have a hierarchy of linked lists where each level is half intervals

Easy to implement if structure is static

Skip Lists [Pugh' 1989]

skipList::insert(k, v) p = gePredecessors(k) for(i = 0; random(2) = 1; i = i+1) {} // random tower height while (i >= P.size()) root = new netinel-only list linked in appropriately P.append(left sentinel of root) p = P.pop() zBelow = new node with (k, v) inserted after p while i > 0 p = P.pop() z = new node with k added after p z.below = zBelow zBelow = z i = i - 1
skipList::delete(k) P = getPRedecessors(k) while P is non-empty p = P.pop() if p.after.key = k p.after = p.after.after else break p = left sentinel of the root-list while p.below.after is the infinity sentinel // the two top lists are both only sentinels, remove one p.below = p.below.below p.after.below = p.after.below.below

Can save number of links stored by storing towers in array

Dynamic ordering