Sub topic 1
Complexity and recurrences: the toolkit for comparing algorithms
Prerequisites
This chapter assumes you know asymptotic notation (Big-O, Theta, Omega), simple recursion, arrays, stacks, queues, binary heaps, and basic graph terms such as vertex, edge, and weighted. You should be able to read Python or C-style pseudocode.
Complexity and recurrences
Time complexity counts how many steps an algorithm takes as the input size n grows. A recurrence expresses the running time of a recursive algorithm in terms of smaller inputs. For example, merge sort satisfies T(n) = 2T(n/2) + O(n), which solves to O(n log n). Every algorithm in this chapter is compared using these tools.
Greedy choices
The greedy-choice property
A greedy algorithm makes the locally best choice at each step and never revisits it. This works only when the problem has the greedy-choice property: some locally best choice belongs to at least one globally optimal solution.
Why a greedy choice is safe: the exchange argument
To prove a greedy choice is safe, take any optimal solution. Swap its first choice for the greedy choice. Show the swapped solution is still feasible and no worse. Repeating this turns any optimal solution into the greedy one.
Activity selection by earliest finish time
Choose the maximum number of non-overlapping activities by always taking the one that finishes first. The sort dominates the cost, giving O(n log n).
def max_activities(intervals):
count = 0
last_end = float('-inf')
for start, finish in sorted(intervals, key=lambda x: x[1]):
if start >= last_end:
count += 1
last_end = finish
return count
print(max_activities([(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11), (8, 12), (2, 14), (12, 16)])) # 4Fractional knapsack by value-to-weight ratio
When items can be split, sort by value per unit weight and fill the bag in that order. Taking a fraction of the last item is allowed, so the greedy answer is optimal. With capacity 50 and items (value, weight) = (60, 10), (100, 20), (120, 30), the answer is 240.
Job sequencing with deadlines and profits
Each job takes one time slot and earns a profit if it finishes by its deadline. Sort jobs by profit, highest first. Place each job in the latest free slot at or before its deadline. Skip the job if no slot is free.
Huffman coding and optimal prefix codes
Huffman coding builds a prefix code, where no codeword is a prefix of another. Repeatedly merge the two lowest-frequency trees into one. Frequent symbols end up near the root, so they get short codes. The exchange argument shows this minimizes the weighted code length.
Dynamic programming
Optimal substructure and overlapping subproblems
A problem has optimal substructure when an optimal solution contains optimal solutions to smaller subproblems. It has overlapping subproblems when a recursive solution solves the same subproblem many times. Dynamic programming stores each subproblem result so it is computed once.
flowchart TD
P["Problem"] --> Q{"Greedy-choice property holds?"}
Q -- Yes --> G["Greedy algorithm with exchange proof"]
Q -- No --> D["Dynamic programming over subproblems"]Memoization and tabulation compared
Memoization is top-down: recurse and cache results. Tabulation is bottom-up: fill a table from base cases. Both take O(n) time for Fibonacci numbers, but tabulation avoids recursion depth limits.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
def fib_tab(n):
if n < 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
print(fib_memo(30), fib_tab(30)) # 832040 832040> Note: the memoized version keeps a cache of up to n entries, as does the table.
Exercise
Three activities are (1, 3), (2, 5), (4, 6). What is the maximum number of non-overlapping activities?
Show answer
2. Pick (1, 3) first, since it finishes earliest. Then pick (4, 6), which starts after 3.