Data Structures and Data Management
Chapter 1 - Introduction
Common facts we will use:
Arithmetic sequence: ∑i=0n−1(a+di)=na+2dn(n−1)∈Θ(n2) if d=0
- we will especially use ∑i=0n−1i=2n(n−1)∈Θ(n2)
Geometric sequence: ∑i=0n−1ari=
- if r>1 then ar−1rn−1∈Θ(rn−1)
- if r=1 then na∈Θ(n)
- if 0<r<1 then a1−r1−rn∈Θ(1)
Harmonic sequence: Hn:=∑i=1ni1=ln(n)+γ+o(1)∈Θ(logn)
- where γ≈0.57721
- ∑i=1ni21=6π2∈Θ(1) and
- ∑i=1nik∈Θ(nk+1) for k≥0
Logarithms:
- c = logb(a) means bc=a
- log(a) in this course always means log2(a)
- log(a⋅c)=log(a)+log(c), log(ac)=clog(a)
- logb(a)=logc(b)logc(a)=loga(b)1, alogb(c)=clogb(a)
- ln(x) = natural log = loge(x), dxdln(x)=x1
- concavity: λlog(x)+(1−λ)log(y)≤log(λx+(1−λ)y) for 0≤λ≤1
Factorial:
- n!=n(n−1)⋯2⋅1 = number of ways to permute n elements
- log(n!)=log(n)+log(n−1)+⋯+log(2)+log(1)∫Θ(nlog(n))
Probability and moments:
- Lineartiy of expectation: E[aX]=aE[X],E[X+Y]=E[X]+E[Y], where X,Y are random variables and E[⋅] denotes the expected value
- If X is a random variable that takes on only non-negative integer values, then E[X]=∑i=0∞i⋅P(X=i)=∑i=1∞P(X≥i)
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:
- Sorting Problem
- Search Problem
- structured search: we search by keys where eat item is usually a key-value-pair
- unstructured search: we do not know what type of search will be happening
Searching will occupy the bulk of this course.
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.
- it is correct if every possible isntance the algorithm obtains the correct output (such algorithm solves the problem)
Computer model
We are using the Random Acecss Machine (RAM) model:
- Consists of memory cells which store one item number (cells are commonly called computer words but we will use words to refer to strings so we stick with cells)
- There is no limit on the number of memory cells that the algorithm can use
- this is not too realistic, but in the age of cheap cloud memory it's not too unrealistic
- Memory cell is big enough to store an integer we deal with
- this is not realistic: The computer either stores 32 or 64 bit numbers, but the RAM model is a model not a computer so if a number is too big it should be treated as a word not a number.
- Any primitive operation should take the same amount of time.
- addition, subtraction, multiplication, division, taking mod, rounding, comparison, and control operations of accessing a memory cell, calling a sub-routine, entering a loop, breaking or returning.
- assuming these all take the same time is unrealistic.
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) I is the number of memory cells it takes.
- the run-time is measured relative to this size
We consider the worst case to calculate the run-time (gives a guaranteed upper bound).
- this sometimes doesn't make sense to use, but computing average run-time is more challenging
1.3 - Asymptotic Notation
Definition 1: Let f(n),g(n) be two functions. We say that f(n)∈O(g(n)) if there exists c>0 and n0≥0 such that ∣f(n)∣≤c∣g(n)∣ for all n≥n0.
- we sat f is in big-O of g (technically we should always mention "asymptotically")
- we abbreviate and say for sufficiently large n
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) is also in O(n100))
We want to say "the run-time is quadratic and we can't get any better than that"
- the second part of the statement is expressed with "big-Omega" denoted Ω
- also called asymptotic lower bound
Definition 2: Let f(n),g(n) be two functions. We say f(n)∈Ω(g(n)) if there exists c>0 and n0≥0 such that ∣f(n)≥c∣g(n)∣ for all n≥n0
- note this definition is exactly the same as big-O except that the inequality is reversed
Definition 3: Let f(n),g(n) be two functions. We say f(n)∈Θ(g(n)) if f(n)∈O(g(n)) and f(n)∈Ω(g(n)). So there exist constants n0≥0 and c1,c2>0 such that c1∣g(n)∣≤∣f(n)∣≤c2∣g(n)∣ for all n≥n0
- "f(n) is asymptotically the same as g(n)", "the run-time is Θ(n2)", "the run-time is O(n2) and this is tight"
- for meaningful bounds we should always use Θ
Growth rates
T(n) is the run-time of some algorithm.
Cmmon growth rates have names:
- constant if T(n)∈Θ(1) we also say T(n)≈c for some constant c which is short for "c≤T(n)≤c′" for some constants c,c′
- logarithmic if T(n)∈Θ(log(n)) i.e, T(n)≈c⋅log(n)
- linear if T(n)∈Θ(n) i.e, T(n)≈cn
- linearthmic if T(n)∈Θ(n⋅log(n)) i.e, T(n)≈c⋅n⋅log(n) (this name is rarely used but the run-time is very common)
- quadratic if T(n)∈Θ(n2) i.e, T(n)≈c⋅n2
- polynomial if T(n)∈Θ(nd)
- exponential if T(n)∈Θ(bn) for some const b>1 (very bad run-time)
Friends of O and Ω
Definition 4: Let f(n),g(n) be two functions. We say that f(n)∈o(g(n)) if for any constant c>0 there exists an n0≥0 such that ∣f(n)≤c∣g(n)∣ for all n≥n0
We say that f(n)∈ω(g(n)) if for any constant c>0 there exists an n0≥0 such that ∣f(n)∣≥c∣g(n)∣ for all n≥n0.
- "little-o" = "asymptotically strictly smaller"
- "little-omega" = "asymptotically strictly larger"
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)"
With big-O you hold (you get to choose one) one constant c and show that there exists n0. For little-o you must show for any c (particularly any small c) there exists n0
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))
Constant multiplication: K⋅f(n)∈Θ(f(n))
Transitivity: If f(n)∈O(g(n)) and g(n)∈O(h(n)) then f(n)∈O(h(n)) the same holds for Ω
This implies Dominance:
- If f(n) in O(g(n)), and g(n)≤h(n) for all sufficiently large n, then f(n)∈O(h(n))
- the same holds for Ω but g(n)≥h(n) for sufficiently large n
Addition: If f(n)∈O(g(n)) and f′(n)∈O(g′(n)) then f(n)+f′(n)∈\O(g(n)+g′(n))
- the same holds for Ω
Maximum-rule for O: If a function h(n) belongs to O(f(n)+g(n)) then it belongs to O(max{f(n),g(n)}). Here max{f(n),g(n)} denotes the function that takes the pointwise
maximum, i.e., for every n it takes on whichever value of f(n) and g(n) is the bigger one.
Maximum-rule for O: If a function h(n) belongs to Ω(f(n)+g(n)) then it belongs to Ω(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) not O(n)<O(n2)
- you cannot add sets with +
Lemma 1.1: Let f(n), g(n) be two functions that satisfy f(n),g(n)>0 for sufficiently large n$ assume that the limit limn→∞g(n)f(n) exists and call it L. Then ,
f(n)∈
- o(g(n)) if L=0
- O(g(n)) if L<∞
- Ω(g(n)) if L>0
- ω(g(n)) if L=∞
Lemma 1.2: let f(n), g(n) be two functions that satisfy f(n),g(n)>0 for sufficiently large n. Then f(n)∈o(g(n)) if and only if limn→∞g(n)f(n) exists and equals 0.
Polynomial rule: If f is a polynomial with leading term cd⋅nd then f(n)∈Θ(nd)
Logarithm rule:
- logb(n)∈Θ(log(n)) for b>1
- all logarithms grow the same asymptotically
- log(n)∈o(n)
- logarithms grow much slower than linear functions
Relationships between asymptotic notations: A
Lemma 1.4: Let f(n),g(n) be two functions with f(n),g(n)>0 for sufficiently large n. If f(n)∈Ω(g(n)) then f(n)∈/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 Θ-notation (tight bounds).
- should also analyze auxiliary space
Comparing algorithms
We consider one algorithm to be worse if its run-time is asymptotically strictly smaller (little-o).
- if it is a tie we use space or other other run-time cases
- using worst-case is far from a perfect solution (O(n^3) > O(10^20 * n^2))
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
- we need two fragments, the merge-routine and the merge-sort
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
- the two parts of the array were sorted before and copy over the smaller item. We split the array in two parts and sort each recursively and since merge is correct the end result is sorted.
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)+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).
- this resolves to T(n)∈Θ(n⋅log(n))
There is a table for finding Θ for recursive expressions.
We should also discuss space
- merge-sort allocates another array of size in so it takes $$\Theta(n)$$ auxiliary space.
- the function calls in the stack take Θ(log(n)) calls but they are dominated by the array allocation
1.5 - Take-home messages
- To describe an algorithm we state the main idea, give detailed description (pseudo-code), argue correctness, analyze run-time and ausxiliary space.
- To compare to algorithm we compare worst-case run-times. Break ties by other considerations such as space and/or best-case run-time.
- Asymptotic notation is a way to express bounds without dealing with constants.
- Bounds on run-time and space should always be states as tight bounds
Algorithm merge-sort solves the sorting problem in Θ(nlog(n)) run-time and uses Θ(n) auxiliary space.
Module 2
Stack ADT
- push: inserting an item
- pop: removing an item
LIFO (last-in first-out)
Extra operations:
We can implement this with an array or a linked-list
Queue ADT
- enqueue: inseting an item
- dequeue: removing the least recently inserted item
FIFO (first-in first-out)
circular array
- keep track of front and end
Priority Queue
An ADT consisting of items each with a priority
main operations
- insert: inserting an item tagged with a priority
- deleteMax: removing the item of highest priority
deleteMax is also called
- the priority is also called a key
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()
- run-time is the sum of insertion and deletion
- will depend on how we implement PQ
note: we usually assyme dynamic arrays i.e, expanding by doubling and so ammortized over all insertions this takes O(1) extra time
Suppose we start from an array A of length 1, we can do n insertions n=2k
- the cost of these insertions is
- O(n times1+1+1+⋯+(1+2+⋯2k−1=2k−1=n−1))=O(n)
- so we see that the additional cost of resizing does not change the insertion run-time from O(n)
Realization 1: unsorted arrays
Using unsorted arrays
- PQ-sort is O(n2) is selection sort
Realization 2: sorted arrays
- insert O(n)
- deleteMax: O(1)
PQ-sort with sorted arrays is insertion sort, the runtime is O(n2)
Binary Heaps
A (binary) heap is a certain type of binary tree
A binary tree is either
- empty or
- consists of three parts
- a node and two binary trees (left subtree and right subtree)
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)
- the height of a non-empty tree is the length of the longest path from the root to a ndoe
- the height of the empty tree is −1
A heap is a binary tree with the following two properties:
- Structural property: All levels of a heap are completely filled, except (possibly) for the last level. The filled items in the last level are left-justified
- Heap-order property: For any node i, the key of the parent of i is larger than or equal to the key of i
The full name for this is a max-oriented binary heap.
Lemma: The height of a heap is Θ(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.
-
The root at A[0] then level 2 is A[1],A[2] and level 3 is A[3]...A[6]
-
the root is at index 0
-
the left child of node i (if it exists) is node 2i−1
-
the right child of node i (if it exists is node 2i+1
-
the parent of node i is ⌊2i−1⌋
-
the last node is n−1
we wrap these operations in root(), parent(i), last(n)
Insert in Heaps
- place the new key at the first free leaf (this must be done to maintain structure)
- the heap-order property might be violated: perform a fix-up
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)
- the new item "bubbles up" until it reaches its correct place in the heap
- runtime: $$O(\textrm{height of heap) = O(log(n))$$
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]
- insert and deleteMax: O(logn)
Time: O( 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
- Heaps can be built faster if we know all input in advance
- Can use the same array for input and heap -> 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))
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
- Binary Heap: A binary tree that satisfies structural and heap-order property
- Heaps are on possible realization of ADT PriorityQueue:
- insert takes O(log n)
- deleteMax takes O(log n)
- Also supports findMax in time O(1)
- A binary heap can be built in linear time
- PQ-sort with binary heaps leads to a sorting algorithm with O(n log n) worst-case run-time (HeapSort)
- We have seen here the max-oriented version of heaps (the maximum priority is at the root)
- there exists a summetric min-oriented version that supports insert and deleteMin with the same runtimes
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
- key
- some data (the value)
operations:
- search(k) (also called findElement(k))
- insert(k, v) (also called insertItem(k,v))
- delete(k) (also called removeElement(k))
- optional: closestKeyBefore, join, isEmpty, size, etc.
Examples: symbol table, license plate databse
Elementary Implementations
- assumptions
- dictionary has n KVPs (key value pairs)
- Each KVP uses constant space
- Keys can be compared in constant time
Unordered array or linked list
- search O(n)
- insert O(1) (except array occasionally needs to resize)
- delete O(n) (need to search)
Ordered array
- search (log n) (via binary serach)
- insert O(n)
- delete O(n)
Binary Search Trees (review)
Structure:
- binary tree: all nodes have two (possibly empty) subtrees
- Every node stores a KVP
- Empty subtrees usually not shown
Ordering:
- Every key k in T.left is less than the root key
- Every key k in T.right is greater than the root key
BST as a realization of ADT Dictionary
BST::search(k)
BST::delete(x)
- if x is a leaf just delete it
- if x has one non-empty subtree just move the children up
- else, swap x with successor (one step right in tree, then left as much as possible)
- this successor node will not have a left child because of the way we reached it (as far left)
- then we can just swap with x and delete
- All of these have complexity O(h) where h is height
- in a normal BST h has no reason to be less than n
AVL Trees
AVL Tree : a BST with extra property
- height of left and right subtree differ by at most 1
Rephrase: If node v has subtree L and R
- balance(b) := height(R) - height(L) must be in [-1, 0, 1]
- balance(v) = -1 is left-heavy
- balance(v) = 1 is right-heavy
Need to store the height of each subtree at every node
- we could save space using only balance(v) at each node but it complicates the code
Height of an AVL Tree
Theorem: An AVL tree on n nodes has O(log n) height
- search, insert, delete all cost O(log n) in the worst case
AVL::insert(k, v)
- first insert(k, v) with usual BST insertion
- assume that this returns the new leaf z where the key was stored
- move up from tree from z, updating hieght
- assume that we have parent-links. we could avoid this if BST::insert returns full path to z
- if the height difference becomes +2,-2 at node z, then z is unbalanced must re-structure the tree to rebalance
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
- Balanced search trees (AVL trees)
- O(log n) worst case search, insert and delete
- complex code and not necessarily the fastest run time in practice
- BST
- O(height) search, insert, and delete
- simpler than AVL tree
- randomization helps efficiency
- Ordered array
- simple implementation
- O(log n) search
- O(n) search and delete
- Ordered linked list
- simple implementation
- O(n) search, insert and delete
- search is the bottleneck, insert and delete would be O(1) if do search first and account for its running time separately
- efficient search (like binary search) in ordered linked list?
Skip Lists
Motivation:
- Ordered array has efficient binary search
We have a hierarchy of linked lists where each level is half intervals
- we visit at most two items at each level
- log n height for the hierarchy
Easy to implement if structure is static
- it is hard to insert and delete in this thing
Skip Lists [Pugh' 1989]
- A hierarchy of S ordered linked lists (levels)
- S0 contains the KVPS of S in non-decreasing order
- other lists store only keys or linkes to nodes in S0
- each Si contains special keys (sentinels) −∞ and +∞
- each Si is randomly generated subsequence of Si−1
- Sh contains only sentinels, the left sentinel is the root
- each node p has references to after(p) and below(p)
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
- best static ordering is by frequency
- dynamic idea:
- move-to-front-heuristic
- can show this is "2-competitive" no worse than twice as bad as the best static ordering
- transpose-heuristic: swap with previous