TExcelTAD
Home › Online Algorithms & Competitive Analysis › Online Algorithms: What This Course Covers

Online Algorithms: What This Course Covers

An online algorithm reads its input one piece at a time and must act on each piece before the next one arrives. A cache must evict a page now, not after seeing tomorrow's requests; an ad platform must assign an ad slot the moment a search query arrives; a robot must move towards a call before it learns where the next call will come from. The decisions are irrevocable, so the algorithm pays for not knowing the future. Competitive analysis measures that price: it compares the online algorithm on every input with the best offline solution, the one chosen with the whole input in hand.

Part I closed with a first look at the subject (Online Problems and the Competitive Ratio, Ski Rental and Move-to-Front). This course, a Part II course of the track, goes much further: it pins down the definitions (strict and non-strict ratios, three kinds of adversaries), proves the main upper and lower bounds with full arguments, and follows the field from paging to metrical task systems, the kk-server problem and online matching.

The topic order follows the standard graduate text, Online Computation and Competitive Analysis by Borodin and El-Yaniv (1998), and, for the last section, the survey The Design of Competitive Online Algorithms via a Primal-Dual Approach by Buchbinder and Naor (2009). Every explanation, program and exercise here is written from scratch. Results are cited by their authors and year so that you can find the original papers.

A taste in one program

Three of the course's problems in a few lines each: renting skis without knowing the season's length, evicting cache pages without knowing future requests, and matching arriving customers to offline items.

python · try it yourself
import random

rng = random.Random(4)

# 1. Ski rental: renting costs 1 a day, buying costs B. Rent until day B - 1, buy on day B.
B = 10
def break_even(days):
    return days if days < B else (B - 1) + B
worst = max(break_even(d) / min(d, B) for d in range(1, 60))
print(f"ski rental, B = {B}: worst ratio of break-even = {worst:.2f}  (theory 2 - 1/B = {2 - 1 / B:.2f})")

# 2. Paging: LRU against Belady's offline rule on a request stream with locality.
def lru(reqs, k):
    cache, misses = [], 0
    for p in reqs:
        if p in cache:
            cache.remove(p)
        else:
            misses += 1
            if len(cache) == k:
                cache.pop(0)
        cache.append(p)
    return misses

def belady(reqs, k):
    cache, misses = set(), 0
    for t, p in enumerate(reqs):
        if p in cache:
            continue
        misses += 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 misses

reqs, page = [], 0
for _ in range(400):
    page = (page + rng.choice([-1, 0, 1, 1, 5])) % 20     # mostly small steps, sometimes a jump
    reqs.append(page)
print(f"paging, k = 4: LRU {lru(reqs, 4)} misses, OPT {belady(reqs, 4)} misses")

# 3. Online matching: customers arrive, each takes the first free item it likes.
likes = {f"c{j}": [f"i{i}" for i in range(j, 6)] for j in range(6)}  # c0 likes all, c5 likes only i5
taken, greedy = set(), 0
for c in [f"c{j}" for j in range(6)]:
    free = [i for i in reversed(likes[c]) if i not in taken]          # an unlucky tie-break
    if free:
        taken.add(free[0])
        greedy += 1
print(f"matching: greedy matched {greedy} of 6 customers; a perfect matching exists")
ski rental, B = 10: worst ratio of break-even = 1.90  (theory 2 - 1/B = 1.90)
paging, k = 4: LRU 232 misses, OPT 182 misses
matching: greedy matched 3 of 6 customers; a perfect matching exists

The three numbers preview three themes. The break-even ratio 2−1/B2 - 1/B is the best any deterministic strategy can guarantee, and a randomized one gets about 1.581.58. LRU's miss count stays within a factor kk of the offline optimum on every sequence, and on sequences with locality it is far closer. Greedy matching always finds at least half of a maximum matching, and the randomized RANKING algorithm guarantees 1−1/e≈0.6321 - 1/e \approx 0.632 in expectation.

How much randomness is worth

A recurring theme of the course is the gap between deterministic and randomized algorithms. For paging with a cache of kk pages, the best deterministic ratio is kk, the best randomized ratio against an oblivious adversary is the harmonic number HkH_k, and the simple marking algorithm achieves 2Hk−12H_k - 1. The program tabulates the three for growing caches.

python · try it yourself
from math import log

print("     k   deterministic k   randomized H_k   marking 2H_k - 1   ln k")
for k in [2, 4, 8, 16, 64, 256, 1024, 65536]:
    H = sum(1 / i for i in range(1, k + 1))
    print(f"{k:6}   {k:15}   {H:14.2f}   {2 * H - 1:16.2f}   {log(k):5.2f}")
     k   deterministic k   randomized H_k   marking 2H_k - 1   ln k
     2                 2             1.50               2.00    0.69
     4                 4             2.08               3.17    1.39
     8                 8             2.72               4.44    2.08
    16                16             3.38               5.76    2.77
    64                64             4.74               8.49    4.16
   256               256             6.12              11.25    5.55
  1024              1024             7.51              14.02    6.93
 65536             65536            11.67              22.34   11.09

The deterministic ratio grows linearly with the cache, the randomized ones only logarithmically: for a cache of 65536 pages, about 11.7 against 65536. Whether randomization helps this much depends on the adversary model, which is why every randomized bound in the course names its adversary.

What the course covers

Section Topics Main results
Competitive analysis online vs offline, strict and non-strict ratios, oblivious and adaptive adversaries, Yao's principle Cobl≤Cad-on≤Cad-off=CdetC_{\text{obl}} \le C_{\text{ad-on}} \le C_{\text{ad-off}} = C_{\text{det}}; lower bounds from input distributions
Ski rental the break-even rule, its lower bound, the randomized distribution, multislope and learning-augmented variants 2−1/B2 - 1/B deterministic; ee−1\frac{e}{e-1} randomized, both tight
Paging Belady's rule, LRU and FIFO, resource augmentation, the marking algorithm, randomized lower bounds kk deterministic; kk−h+1\frac{k}{k-h+1} against a cache of hh; 2Hk2H_k for marking, HkH_k lower bound
List update move-to-front, transpose, frequency count, randomized BIT MTF 2-competitive by a potential function; transpose and frequency count are not competitive
Metrical task systems and kk-server definitions, the kk-server conjecture, double coverage, the work-function algorithm, randomized kk-server 2n−12n - 1 for MTS; kk on lines and trees; 2k−12k - 1 for the work-function algorithm; the 2023 Ω(log⁡2k)\Omega(\log^2 k) refutation
Online matching and allocation greedy, RANKING, AdWords, the online primal-dual method 12\frac{1}{2} for greedy; 1−1e1 - \frac{1}{e} for RANKING and for MSVV with small bids; O(log⁡d)O(\log d) fractional set cover

The Exercises collect problems from every section, and the Mini Project builds a cache-eviction arena that replays request traces against LRU, FIFO, the marking algorithm, OPT and an adversary, and reports the measured competitive ratios.

What you should know first

  • Part I of the track, especially the online lessons of Selected Topics and the potential method from Amortized Analysis.
  • Probability: expectation, linearity, conditional expectation. The randomized lessons use nothing beyond Expectation Tricks.
  • Linear programming duality for the last section, at the level of writing down a dual. The course LP Duality treats it in depth; the matching lessons recall what they need.

Conventions

  • A request sequence is σ=σ1σ2⋯σn\sigma = \sigma_1 \sigma_2 \cdots \sigma_n. ALG(σ)\mathrm{ALG}(\sigma) is the cost of the online algorithm and OPT(σ)\mathrm{OPT}(\sigma) the optimal offline cost. For maximization problems (matching, AdWords) the ratio is written as a number at most 1: ALG≥c⋅OPT\mathrm{ALG} \ge c \cdot \mathrm{OPT}.
  • Every bound states its kind: strict (no additive constant) or non-strict, deterministic or randomized, and for randomized algorithms the adversary it holds against. Results that are only sketched, or that are open problems, are marked as such.
  • Hk=1+12+⋯+1kH_k = 1 + \frac{1}{2} + \cdots + \frac{1}{k} is the kk-th harmonic number, ln⁡k<Hk≤1+ln⁡k\ln k < H_k \le 1 + \ln k.
  • Every random choice in a program comes from a generator with a fixed seed (random.Random(seed) in Python, std::mt19937 in C++), so the printed numbers are exactly what you will see. Python and C++ use different generators, so their measured averages differ slightly; the text says so each time.
  • Pseudocode is in the track's style (How to read pseudocode).

Test yourself

What distinguishes an online algorithm from an offline one?

  1. It runs on a server
  2. It must serve each request before seeing the next one, and its decisions are irrevocable
  3. It is always randomized
  4. It is allowed to be slower

Competitive analysis compares an online algorithm with what?

  1. The average-case cost of the same algorithm
  2. The optimal offline cost on the same input, for every input
  3. The best other online algorithm
  4. A lower bound on running time

For a maximization problem such as online matching, how is a competitive ratio of 1−1/e1 - 1/e to be read?

  1. The algorithm's value is at most (1−1/e)(1 - 1/e) times the optimum
  2. The algorithm obtains at least (1−1/e)(1 - 1/e) times the optimal value
  3. The algorithm loses 1/e1/e items in total
  4. The ratio is undefined for maximization