Exercises
Fourteen problems covering the whole course: competitive ratios and adversaries, ski rental, paging, list update, -server and online matching. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.
Tip: For an upper bound, look for a potential function or a phase decomposition and compare the algorithm with OPT phase by phase. For a lower bound, decide first whether you need it for deterministic algorithms (build the sequence adaptively) or for randomized ones (choose an input distribution and use Yao's principle), and make sure OPT grows without bound if the bound is non-strict.
| # | Exercise | Practises |
|---|---|---|
| 1 | List scheduling, tight | strict ratios |
| 2 | The wrong buying day | deterministic ski rental |
| 3 | Randomized ski rental for | deriving the distribution |
| 4 | The hard distribution for | Yao's principle |
| 5 | Randomness that leaks | adaptive adversaries |
| 6 | Belady's anomaly | Belady, FIFO, LRU |
| 7 | Counting phases | marking and conservative algorithms |
| 8 | How much more memory? | resource augmentation |
| 9 | One phase of MARK | the analysis |
| 10 | Coupon collecting for OPT | the lower bound |
| 11 | One step of move-to-front | the list-update potential |
| 12 | One step of double coverage | the -server potential |
| 13 | RANKING on a small triangle | online matching |
| 14 | Primal-dual ski rental for | the online primal-dual method |
Exercise 1: List scheduling, tight
Graham's list scheduling is -competitive for makespan on machines (The Competitive Ratio, Precisely). For , give a job sequence on which list scheduling has makespan exactly times the optimum. Is this a lower bound on the strict or the non-strict ratio of list scheduling?
Answer
Twelve jobs of size 1, then one job of size 4: list scheduling reaches makespan 7, OPT 4. Since every job can be scaled by any factor , the same ratio holds with for every , so it bounds the non-strict ratio as well.
Solution
The twelve unit jobs spread evenly, three per machine, and the job of size 4 lands on a machine with load 3: makespan 7. OPT puts the size-4 job alone and four unit jobs on each of the other three machines: makespan 4. A single instance only bounds the strict ratio, but multiplying all sizes by multiplies both makespans by , so on instances with arbitrarily large OPT, and no additive constant can help.
Exercise 2: The wrong buying day
Ski rental with : a skier buys on the morning of day 4 if the season is still on. What is the worst-case ratio of this strategy, and which season length attains it? Which buying day is best, and what is its ratio?
Answer
, attained by a 4-day season. The best day is 7, with ratio .
Solution
By the analysis of every deterministic strategy, strategy is worst when the season ends on the purchase day, with ratio . For this is . The function decreases up to and increases after, so is best with .
Exercise 3: Randomized ski rental for
Derive the optimal randomized strategy for (buying day ) by equalizing the expected cost over seasons, and compute its ratio exactly.
Answer
, ratio .
Solution
The recurrence of Randomized Ski Rental gives , so . The ratio is . The program checks that every season length gives this ratio.
from fractions import Fraction as F
B = 3
p = [F(4, 19), F(6, 19), F(9, 19)]
for D in range(1, 6):
cost = sum(pi * ((i - 1 + B) if D >= i else D) for i, pi in enumerate(p, start=1))
print(f"season {D}: E[cost] = {cost}, OPT = {min(D, B)}, ratio = {cost / min(D, B)}")
print("1/(1 - (2/3)^3) =", 1 / (1 - F(2, 3) ** 3))season 1: E[cost] = 27/19, OPT = 1, ratio = 27/19
season 2: E[cost] = 54/19, OPT = 2, ratio = 27/19
season 3: E[cost] = 81/19, OPT = 3, ratio = 27/19
season 4: E[cost] = 81/19, OPT = 3, ratio = 27/19
season 5: E[cost] = 81/19, OPT = 3, ratio = 27/19
1/(1 - (2/3)^3) = 27/19
Exercise 4: The hard distribution for
For ski rental with , find a distribution over seasons (one short season and one long season) on which both deterministic strategies "buy on day 1" and "buy on day 2" have the same expected cost. What lower bound does Yao's principle give?
Answer
. Both strategies cost 2 in expectation, , so no randomized strategy beats , which equals .
Solution
Buying on day 1 costs 2 in both seasons. Buying on day 2 costs 1 in the short season and in the long one. With probability for the short season, the costs are and ; they are equal for . Later buying days cost more on the long season, so they are worse. , and every deterministic strategy has . By Yao's principle, the strict randomized ratio is at least , which the distribution achieves.
Exercise 5: Randomness that leaks
A randomized paging algorithm is -competitive against oblivious adversaries. Its eviction choices are observable by an attacker who also controls the requests (for example through timing). What ratio can the attacker force? What does the theorem of Ben-David et al. say about the existence of a good deterministic algorithm if some randomized paging algorithm were -competitive against adaptive online adversaries?
Answer
Ratio : the attacker is an adaptive adversary and requests the page that is not cached. A -competitive algorithm against adaptive online adversaries would imply a deterministic -competitive one; since deterministic paging cannot beat , such a must satisfy (and in fact by a direct argument).
Solution
With pages and knowledge of the cache, the adversary makes every request a miss, while OPT on the resulting sequence misses at most once every requests (Oblivious and Adaptive Adversaries). The relation gives the weaker ; the direct argument of Raghavan and Snir (1989) shows that adaptive online adversaries force .
Exercise 6: Belady's anomaly
For the request sequence 1 2 3 4 1 2 5 1 2 3 4 5, count the misses of FIFO, LRU and Belady's rule with 3 and with 4 cache slots (empty start). What is surprising?
Answer
| slots | FIFO | LRU | OPT |
|---|---|---|---|
| 3 | 9 | 10 | 7 |
| 4 | 10 | 8 | 6 |
FIFO misses more with the larger cache: Belady's anomaly (Belady, Nelson and Shedler, 1969).
Solution
LRU and OPT are stack algorithms: the cache with slots is always a subset of the cache with slots, so more memory never hurts. FIFO lacks this inclusion property, and this sequence exploits it.
def misses(reqs, k, policy):
cache, count = [], 0
for t, p in enumerate(reqs):
if p in cache:
if policy == "lru":
cache.remove(p)
cache.append(p)
continue
count += 1
if len(cache) == k:
if policy == "opt":
rest = reqs[t + 1:]
cache.remove(max(cache, key=lambda q: rest.index(q) if q in rest else len(rest)))
else:
cache.pop(0)
cache.append(p)
return count
reqs = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
for k in [3, 4]:
print(f"{k} slots: FIFO {misses(reqs, k, 'fifo')}, LRU {misses(reqs, k, 'lru')}, OPT {misses(reqs, k, 'opt')}")3 slots: FIFO 9, LRU 10, OPT 7
4 slots: FIFO 10, LRU 8, OPT 6
Exercise 7: Counting phases
With , split A B C A D A B E B A C D E into phases. Bound the misses of any marking algorithm and of OPT using the phase argument, and compare with the actual counts for LRU and OPT.
Answer
Phases: A B C A | D A B | E B A | C D E, so . Marking algorithms miss at most times; OPT misses at least times (in fact at least with an empty start). LRU misses 9 times and OPT 7 times.
Solution
A phase is the longest stretch with at most distinct pages (LRU and FIFO Are k-Competitive). The program computes the phases and the counts.
def phases(reqs, k):
out, cur = [], []
for p in reqs:
if p not in cur and len(set(cur)) == k:
out.append(cur)
cur = []
cur.append(p)
return out + [cur]
def lru(reqs, k):
cache, m = [], 0
for p in reqs:
if p in cache:
cache.remove(p)
else:
m += 1
if len(cache) == k:
cache.pop(0)
cache.append(p)
return m
def opt(reqs, k):
cache, m = set(), 0
for t, p in enumerate(reqs):
if p not in cache:
m += 1
if len(cache) == k:
rest = reqs[t + 1:]
cache.remove(max(cache, key=lambda q: rest.index(q) if q in rest else len(rest)))
cache.add(p)
return m
reqs = "A B C A D A B E B A C D E".split()
ph = phases(reqs, 3)
print(" | ".join(" ".join(x) for x in ph), f"-> {len(ph)} phases")
print(f"LRU {lru(reqs, 3)} <= k*m = {3 * len(ph)}; OPT {opt(reqs, 3)} >= k + m - 2 = {3 + len(ph) - 2}")A B C A | D A B | E B A | C D E -> 4 phases
LRU 9 <= k*m = 12; OPT 7 >= k + m - 2 = 5
Exercise 8: How much more memory?
The offline optimum has slots. How many slots does LRU need so that the resource-augmentation bound guarantees ratio at most ? At most ?
Answer
for , and for .
Solution
The bound is (Resource Augmentation). . .
Exercise 9: One phase of MARK
A phase of the marking algorithm with has new pages, requested first, followed by the 7 old pages. What is the expected number of misses in the phase? Compare with the cruder bound .
Answer
; the cruder bound is .
Solution
The new pages miss once each. The -th old page misses with probability , : (The Randomized Marking Algorithm). Total .
Exercise 10: Coupon collecting for OPT
Requests are uniform over pages and the cache has slots. What is the expected number of requests between two consecutive misses of OPT? What is every deterministic algorithm's miss rate, and what ratio does this give?
Answer
requests; every deterministic algorithm misses at rate ; the ratio is .
Solution
After a miss, OPT's next miss comes when the last of the 3 pages other than the current one has been requested again: waits of for the three of them, in total (The Harmonic Lower Bound). OPT's long-run miss rate is , and .
Exercise 11: One step of move-to-front
MTF's list is c a d b e and a competitor's list is a b c d e. Item d is requested. Compute MTF's cost , the competitor's position , the change of the inversion potential, and check the amortized bound .
Answer
, , , amortized cost .
Solution
In front of d in MTF's list are c and a, both also in front of d in the competitor's list, so and moving d to the front creates inversions. The amortized cost is (List Update).
def inversions(a, b):
pos = {x: i for i, x in enumerate(b)}
s = [pos[x] for x in a]
return sum(s[i] > s[j] for i in range(len(s)) for j in range(i + 1, len(s)))
mtf, other = list("cadbe"), list("abcde")
before = inversions(mtf, other)
k, i = mtf.index("d") + 1, other.index("d") + 1
mtf.insert(0, mtf.pop(k - 1))
after = inversions(mtf, other)
print(f"k = {k}, i = {i}, Phi {before} -> {after}, amortized {k + after - before} <= {2 * i - 1}")k = 3, i = 4, Phi 3 -> 5, amortized 5 <= 7
Exercise 12: One step of double coverage
Three servers on a line. DC's servers are at 0, 4 and 10; OPT's servers (after OPT has served the request) are at 3, 4 and 12. The request is at 3. Perform DC's move and compute the change of .
Answer
DC moves 0 and 4 by 1 each (to 1 and 3), cost 2. : ; : . .
Solution
The request lies between 0 and 4, so (Double Coverage). The sorted matching pairs before, cost 5, and after, also 5. Pairwise distances: before, after. So , exactly minus DC's cost, as the proof guarantees.
Exercise 13: RANKING on a small triangle
Offline vertices ; online vertices arrive in the order with , , . Compute RANKING's expected matching size exactly by averaging over all 6 rankings, and compare with .
Answer
, a fraction of OPT , above .
Solution
from fractions import Fraction
from itertools import permutations
adj = [[0, 1, 2], [1, 2], [2]]
total = 0
for order in permutations(range(3)):
rank = {u: r for r, u in enumerate(order)}
free, size = {0, 1, 2}, 0
for nbrs in adj:
cands = [u for u in nbrs if u in free]
if cands:
free.remove(min(cands, key=lambda u: rank[u]))
size += 1
total += size
print("E[size] =", Fraction(total, 6), "=", round(total / 6 / 3, 4), "of OPT")E[size] = 13/6 = 0.7222 of OPT
Losses happen when an earlier vertex takes , the only neighbour of ; for example does so with probability . Small instances do better than ; the bound is approached only as the triangle grows (RANKING).
Exercise 14: Primal-dual ski rental for
Run SKI-PRIMAL-DUAL of the primal-dual lesson by hand for . What is , what is after days 1 and 2, and what ratio does the method guarantee? Compare with the optimal randomized ratio for .
Answer
; after day 1 and after day 2; the guarantee is , worse than the optimal of Exercise 4.
Solution
Day 1: . Day 2: . Each day raises the primal by and the dual by 1. The method's constant is tuned for large (where ); for tiny the exact equalizing distribution is much better.
Test yourself
You want a lower bound on the competitive ratio of every randomized algorithm against an oblivious adversary. Which tool fits?
- An adaptive adversary that watches the coins
- Yao's principle: a distribution on inputs that is bad for every deterministic algorithm
- A potential function
- Resource augmentation
Which paging algorithms never suffer Belady's anomaly?
- FIFO
- Stack algorithms such as LRU and OPT, whose -slot cache is always contained in their -slot cache
- Every algorithm
- Only randomized ones
In the double-coverage potential, what is when DC moves two servers by each towards a request between them?
- At most
- Exactly 0