Online Algorithms and Competitive Analysis
A cache must decide, right now, which page to evict. It cannot know what you'll request next. A stock trader holding foreign currency must decide, right now, whether to convert. She cannot know tomorrow's exchange rate. A server assigning arriving jobs to machines must decide, right now, which machine gets the job. It cannot know what jobs will arrive later. In each case, the algorithm sees its input piece by piece. It must commit to irrevocable decisions before the future is revealed. This is fundamentally different from the offline setting studied in Approximation Algorithms and the Approximation Ratio. There, the entire input is known in advance. The only obstacle is computational hardness. Online decision-making is not a curiosity. It is the default condition of real computing systems. Operating systems page memory in real time. Routers forward packets without knowing future traffic. Ride-sharing platforms match drivers to riders as requests stream in. Financial systems execute trades against unknown future prices. In all these settings, "wait and see" is not an option. Yet we still want a rigorous way to say an algorithm is good. This holds even though it cannot possibly match the clairvoyant optimum in every instance. Competitive analysis supplies that rigor. Instead of asking "how close to optimal is this algorithm on average?", competitive analysis asks something else. That average-case question requires a probability model we may not trust. Instead, competitive analysis asks a worst-case question. Across every possible input sequence, how does the online algorithm's cost compare? Compare it to the cost of the best possible algorithm that saw the whole sequence in advance. This ratio — the competitive ratio — plays the same role for online algorithms. That role is the one the approximation ratio plays for NP-hard problems. But the source of difficulty is different. It is not computational intractability but informational incompleteness. An online algorithm can be trivial to compute. It can still be forced into bad decisions purely because it cannot see the future. This article develops the formal framework of competitive analysis. It walks through the canonical case studies — the ski-rental problem and paging/caching. Full proofs of tight competitive ratios are included. It shows how randomization can provably beat every deterministic strategy. It closes with the broader landscape. This includes where these ideas show up in real infrastructure. It also covers the classic pitfalls when reasoning about "the future" an algorithm cannot see.
- An online algorithm must process input piece-by-piece, committing to decisions without knowledge of future input.
- The competitive ratio compares an online algorithm's worst-case cost to that of an optimal offline algorithm (OPT) that sees the entire input in advance.
- An algorithm is c-competitive if its cost is at most `c · OPT + a` for all input sequences, for some additive constant `a`.
- Ski rental shows a clean 2-competitive deterministic algorithm, and this is provably optimal among deterministic strategies.
- Paging (caching): any deterministic eviction policy is exactly `k`-competitive with cache size `k`; randomization improves this to `Θ(log k)`.
- Competitive analysis is the online-decision analogue of the approximation ratio for NP-hardness — the enemy is missing information, not computational limits.
An online algorithm is judged not against perfection, but against the best strategy that would have existed had the future been known — and the tightest such comparison is a worst-case ratio, not an average case.
The idea
An online problem is one in which the input arrives as a sequence of requests `σ = (r₁, r₂, …, rₙ)`, and an algorithm must produce a response to `rᵢ` before it sees `r_{i+1}, r_{i+2}, …`. This is in contrast to the offline setting, where the whole sequence `σ` is available before any decision is made. Many classical algorithmic problems (shortest path, sorting, MST) are naturally offline; online problems arise whenever decisions have real-time deadlines: cache management, job scheduling with arrivals, network routing, financial hedging, and matching markets are all online by nature. To measure quality without assuming a distribution over inputs, we compare against the best possible offline algorithm on the same sequence, denoted `OPT(σ)`. This offline optimum is a moving target: for one sequence it is the cost of one strategy, for another sequence it is the cost of a completely different strategy — it is defined instance by instance as the infimum cost achievable with full knowledge of `σ`. An online algorithm `ALG` is c-competitive (for minimization problems) if there exists a constant `a ≥ 0`, independent of `σ`, such that ``` cost_ALG(σ) ≤ c · cost_OPT(σ) + a for every input sequence σ. ``` The smallest such `c` is the competitive ratio of `ALG`. (For maximization problems the inequality flips: `cost_ALG(σ) ≥ (1/c) · cost_OPT(σ) − a`.) The additive constant `a` is a technical convenience — it allows an algorithm to be penalized on short, unlucky sequences without being disqualified by them — but for most natural problems one can prove strict competitiveness with `a = 0`. Competitive analysis is deliberately adversarial: we imagine an adversary who, knowing the algorithm's (possibly randomized) strategy in advance, constructs the worst possible sequence `σ` to maximize the ratio `cost_ALG(σ)/cost_OPT(σ)`. This is a worst-case guarantee, exactly analogous to how the approximation ratio bounds worst-case solution quality for NP-hard problems — the difference is that here the "hardness" comes from a temporally adversarial input rather than a computationally adversarial instance space. When randomization is introduced, the adversary is assumed oblivious: it fixes the entire sequence in advance, without seeing the algorithm's coin flips, and we compare the algorithm's expected cost to `OPT`. (Stronger adaptive-adversary models exist but the oblivious model is the standard baseline and is what all the ratios below use.)
How it works
Case study 1: Ski rental (the canonical warm-up)
You are about to ski for an unknown number of days. Renting skis costs `B` once, after which skiing is free. You must decide, each morning, whether to rent again or buy — without knowing whether this is your last ski day. This is the prototypical rent-or-buy problem, and it models any scenario with a recurring cost versus a one-time investment (buying vs. leasing hardware, caching a computation vs. recomputing it, JIT-compiling vs. interpreting a code path). The break-even algorithm: rent for the first `B − 1` days; if you are still skiing on day `B`, buy. ``` BREAK-EVEN-SKI-RENTAL(B): day ← 0 bought ← false while trip continues: day ← day + 1 if bought: ski for free today continue if day < B: rent today, pay B bought ← true ```
Claim: this algorithm is 2-competitive, and no deterministic algorithm can do better. Upper bound proof. Let `n` be the (unknown, adversarially chosen) total number of ski days.
- If `n < B`: the algorithm only ever rents, paying `n`. OPT also would have rented (buying costs `B > n`), so `OPT = n`. Ratio is exactly 1.
- If `n ≥ B`: the algorithm pays `(B − 1)` in rent plus `B` to buy, total `2B − 1`. OPT, knowing `n ≥ B` in advance, buys on day 1, paying `B`. So the ratio is
``` (2B − 1) / B = 2 − 1/B < 2. ``` In both cases `cost_ALG(σ) ≤ 2 · cost_OPT(σ)`, so the algorithm is (strictly) 2-competitive. Lower bound proof (optimality among deterministic algorithms). Any deterministic algorithm commits, in advance, to some day `k` on which it will buy if it hasn't stopped. An adversary who knows `k` simply ends the trip on day `k` — the worst possible moment. Two sub-cases:
- If the adversary stops the trip on day `k − 1` (one day before the algorithm would buy), the algorithm has paid `k − 1` in rent, while OPT (knowing the trip is `k−1` days) pays `min(k−1, B)`.
- If the adversary continues to day `k`, forcing the buy, the algorithm pays `(k − 1) + B`, while OPT pays `min(k, B)`.
Optimizing the adversary's choice of `k` against any fixed deterministic threshold shows the ratio cannot be pushed below `2 − 1/B` for any strategy — the break-even point `k = B` is exactly the threshold that balances these two failure modes, and no other threshold does better. Hence 2 is the optimal deterministic competitive ratio for ski rental (in the limit `B → ∞`, the ratio approaches exactly 2, and no deterministic algorithm beats it).
Randomization helps. If the algorithm may randomize its buying day according to a carefully chosen distribution over `{1, …, B}`, the expected competitive ratio against an oblivious adversary drops to `e/(e−1) ≈ 1.58`, strictly better than the deterministic bound of 2. This mirrors a recurring theme: randomized online algorithms can provably beat the best possible deterministic one, because the adversary must commit to a sequence before seeing the coin flips.
Case study 2: Paging / caching
A cache holds `k` pages; a sequence of page requests arrives one at a time. On a hit (requested page already in cache) there is no cost. On a miss, the algorithm must evict some page from the cache to make room, incurring one unit of cost, and cannot see future requests when deciding whom to evict. The offline optimum, Bélády's algorithm (evict the page whose next use is furthest in the future, or is never used again), is known to be optimal offline — but it requires knowledge of the future and is thus not implementable online. ``` LRU-PAGING(k): // Least-Recently-Used online algorithm cache ← empty set, |cache| ≤ k for each request p in the input sequence: if p ∈ cache: mark p as most-recently-used // hit, no cost else: if |cache| == k: evict the least-recently-used page in cache insert p into cache, mark as most-recently-used cost ← cost + 1 // miss ```
Claim: LRU (and in fact every "reasonable" deterministic algorithm) is k-competitive, and this is the best possible ratio for any deterministic online paging algorithm. Upper bound sketch (LRU is k-competitive). Partition the request sequence into maximal blocks such that each block contains exactly `k` distinct page misses under LRU (the last block may be shorter). Within any such block of `k` distinct pages, an offline algorithm with a cache of size `k` can have at most one miss on the pages that were already resident before the block began, because a block by construction touches `k` distinct new pages and the cache only holds `k` slots — forcing at least one eviction somewhere is unavoidable once `k+1` distinct pages have been seen since a slot was last free. Careful accounting (the standard potential function or phase-partition argument) shows LRU incurs at most `k` misses per block while OPT incurs at least 1, giving a ratio of `k`. Lower bound (deterministic paging cannot beat k). Fix any deterministic algorithm `ALG` with cache size `k`. An adversary who knows `ALG`'s eviction rule can always request the one page, among `k+1` candidate pages, that `ALG` currently does not have cached — forcing a miss on every single request. Meanwhile an offline algorithm, seeing the whole sequence, only needs to evict a page when a new page among the `k+1` candidates is requested for the first time in a while — and with `k+1` total pages cycling and a cache of size `k`, OPT can arrange to miss only once every `k` requests (it evicts the one candidate page not needed again soonest, à la Bélády). This forces the ratio `ALG`/`OPT` up to `k` in the worst case, matching the upper bound exactly. So k is the tight, optimal deterministic competitive ratio for paging with cache size `k` — a clean, famous result.
Randomization helps again. The randomized MARKING algorithm — mark a page on access, evict a uniformly random unmarked page on a miss, unmark everything once all pages are marked — achieves a competitive ratio of `Θ(log k)` (specifically `2 H_k − 1` where `H_k` is the `k`-th harmonic number) against an oblivious adversary, an exponential improvement over the deterministic bound of `k`. This is one of the most striking demonstrations in the whole field that hiding your randomness from the adversary is a genuinely powerful resource, not just an analytical convenience.
Complexity & correctness
Time and space complexity of the algorithms themselves are usually modest — the interesting complexity in this topic is not computational cost but the information-theoretic cost of not knowing the future, quantified via the competitive ratio.
- Ski rental: `O(1)` time per day, `O(1)` space (just a counter and a boolean). The competitive-ratio analysis is `O(1)` bookkeeping — the two-case argument above.
- LRU paging: with a doubly linked list plus a hash map from page → list node, both lookup and "move to front" take `O(1)` amortized time, and the structure uses `O(k)` space for a cache of size `k`. The `k`-competitiveness proof requires only the phase-partition argument, not any extra runtime cost.
- MARKING (randomized paging): `O(1)` expected time per request with an appropriate data structure tracking marked/unmarked pages, `O(k)` space; the `Θ(log k)` ratio is a purely analytical result about expected cost, not a runtime cost.
Correctness of the competitive-ratio claims rests on two complementary arguments, and it is worth being explicit about the proof pattern, since it recurs across almost every online problem: 1. Upper bound (the algorithm is at least this good). Exhibit an explicit accounting scheme — a potential function, a charging argument, or an explicit case split — that bounds `cost_ALG(σ)` in terms of `cost_OPT(σ)` for every sequence `σ`, with no assumption on `σ`'s distribution. In ski rental this was a two-case split; in paging it was the phase/block decomposition. 2. Lower bound (no algorithm — in this model — can do better). Construct an adversary strategy that, played against an arbitrary algorithm of the given type (deterministic, or randomized against an oblivious adversary), forces the ratio up to the claimed bound. This is what proves optimality, not just correctness — it is the online-algorithms analogue of an NP-hardness reduction: it certifies that no cleverer algorithm within the model can escape the bound. Both halves are necessary: an upper bound alone only shows one algorithm is "good enough," while the matching lower bound shows the problem itself, not the particular algorithm, is inherently this hard online. When the two bounds coincide (as in ski rental's `2` and paging's `k`), the ratio is called tight, and we have fully characterized the online price of not knowing the future.
Honest tradeoffs. Competitive analysis is a worst-case framework by design — it deliberately ignores the "typical" input distribution a real system might see, which is both its strength (no assumptions needed, robust guarantees) and its weakness (an algorithm can be competitively "optimal" yet perform poorly on realistic, non-adversarial traffic; LRU with ratio `k` is far better in practice than the worst case suggests, because real access patterns exhibit locality that the adversary's construction ignores). Refinements such as access-graph models, loose competitiveness, and comparing against a restricted class of offline algorithms exist precisely to recover more realistic guarantees, at the cost of extra modeling assumptions.
Worked example
Trace the ski-rental algorithm with `B = 4` (buy price $4) against three different adversarial trip lengths, and compare to the true offline optimum for each.
| Trip length `n` | ALG's payments | ALG total | OPT (knows `n`) | OPT total | Ratio |
|---|---|---|---|---|---|
| `n = 1` | rent day 1 | $1 | rent (cheaper than buying) | $1 | 1.00 |
| `n = 3` | rent days 1,2,3 | $3 | rent all 3 days (< $4) | $3 | 1.00 |
| `n = 4` | rent days 1–3 (4) | $7 | buy on day 1 | $4 | 1.75 |
| `n = 100` | rent days 1–3 (4), free after | $7 | buy on day 1 | $4 | 1.75 |
The worst ratio, `7/4 = 1.75`, occurs exactly at the break-even trip length `n = B = 4` and never gets worse no matter how much longer the trip runs, since both ALG's and OPT's costs saturate at `2B − 1` and `B` respectively. This matches the general bound `2 − 1/B = 2 − 1/4 = 1.75` derived above — confirming the formula on a concrete instance, not just asymptotically. Now trace LRU paging with cache size `k = 3` on the request sequence `A, B, C, A, D, A, B, C`:
| Step | Request | Cache before | Hit/Miss | Evicted | Cache after |
|---|---|---|---|---|---|
| 1 | A | { } | Miss | — | {A} |
| 2 | B | {A} | Miss | — | {A,B} |
| 3 | C | {A,B} | Miss | — | {A,B,C} |
| 4 | A | {A,B,C} | Hit | — | {A,B,C} (A refreshed) |
| 5 | D | {A,B,C} | Miss | B (least recently used) | {A,C,D} |
| 6 | A | {A,C,D} | Hit | — | {A,C,D} |
| 7 | B | {A,C,D} | Miss | D (least recently used) | {A,B,C}... wait, C not evicted |
| 8 | C | current cache | Hit | — | — |
LRU incurs 5 misses (steps 1,2,3,5,7) and 3 hits out of 8 requests. The offline optimum with foresight (Bélády's rule: evict the page whose next use is furthest away) can do strictly better here: at step 5, knowing that `B` is not needed again but `A` is needed at step 6, Bélády would still evict `B` (matching LRU in this case) — but on longer adversarially constructed sequences the gap between LRU and Bélády widens toward the full factor of `k`, which is exactly what the tight lower-bound construction (cycling through `k+1` pages) is designed to expose. This small trace illustrates the mechanism — eviction under uncertainty — even though it does not itself hit the full worst-case ratio, which requires a longer, carefully adversarial sequence over `k+1` pages.
Common pitfalls & traps
| Pitfall | Why it's wrong | Fix |
|---|---|---|
| Comparing ALG to the average-case offline cost instead of worst-case OPT per instance | Competitive ratio is defined instance-by-instance against OPT(σ), not against one fixed benchmark or a distributional average | Always define OPT as a function of the same σ the algorithm sees |
| Forgetting the additive constant `a` and demanding `cost_ALG ≤ c·OPT` exactly | Many algorithms are only competitive with a constant offset; omitting `a` can make a genuinely good algorithm look non-competitive on tiny instances | State the definition with `+a` unless you've proven the stricter `a=0` bound |
| Assuming a randomized algorithm's competitive ratio holds against an adaptive adversary | The standard `Θ(log k)` paging bound is proven against an oblivious adversary who commits to σ before seeing coin flips; adaptive adversaries can do much worse to the algorithm | Always state which adversary model (oblivious / adaptive-online / adaptive-offline) the ratio assumes |
| Treating "k-competitive" as "bad" without noting it is tight and unavoidable for deterministic paging | k is not a weakness of LRU specifically — it is a lower bound on every deterministic algorithm, so no cleverer deterministic policy escapes it | Check whether a poor-looking ratio is actually the best possible in that model before blaming the algorithm |
| Using worst-case competitive ratio to predict real-world (non-adversarial) performance | Real traffic has locality; the adversary's construction is deliberately pathological and rarely occurs naturally | Complement worst-case ratios with empirical/locality-aware models (access graphs, working-set analysis) when tuning production systems |
Pioneers & history
Competitive analysis crystallized as a named framework in the 1980s, though its roots trace to earlier work on real-time scheduling and rent-to-buy tradeoffs.
Origins · 1 minDaniel Dominic Sleator and how this was discovered
Sleator, working with Robert Tarjan, formalized the comparison between an online algorithm and an offline optimum as a general analytical tool, coining the term "competitive ratio" in their landmark 1985 paper on list-update and paging algorithms. Their work established both the deterministic k-competitiveness of paging and set the stage for the randomized results that followed, giving the field its central proof technique: exhibit an accounting scheme for the upper bound, and an adversary construction for the matching lower bound.
Where this matters
Operating systems and hardware caches. Virtual memory page-replacement, CPU cache eviction (LRU-approximations like the clock algorithm), and CDN edge-cache policies are all direct engineering instances of the online paging problem; the k-competitiveness bound explains precisely why no deterministic eviction rule can be a silver bullet, and it motivates practical heuristics (LRU-K, ARC, CLOCK) that trade provable worst-case guarantees for better locality-aware average behavior.
Networking and routing. Online algorithms for buffer management, packet scheduling under unknown arrival patterns, and adaptive routing all use competitive-ratio analysis to bound worst-case degradation versus an omniscient offline router.
Financial and resource-allocation systems. The ski-rental tradeoff directly models cloud-instance reservation decisions (reserve vs. on-demand pricing), currency-conversion timing, and any "commit now vs. wait" decision under uncertainty; competitive analysis gives provable worst-case bounds where classical decision theory would need a (possibly unjustified) probability model.
Online matching and ad allocation. Ad-exchange platforms matching arriving queries to advertisers, and ride-sharing platforms matching arriving riders to drivers, are modeled as online bipartite matching — the Karp–Vazirani–Vazirani algorithm's `1 − 1/e` competitive ratio for randomized online matching underlies theoretical analyses of real ad-auction systems.
Algorithms with predictions. Modern research augments classical online algorithms with untrusted machine-learned forecasts (e.g., predicted future page-access patterns, predicted job sizes), asking for algorithms that are provably competitive in the worst case yet perform close to OPT when predictions are accurate — directly extending the framework developed here, and connecting online algorithms to the broader landscape of Heuristics and Local Search and modern learning-augmented systems design.
Ask the tutor: How does the randomized MARKING algorithm's Θ(log k) competitive ratio proof actually work, step by step?
Is competitive analysis the same as approximation-ratio analysis?
They share the same mathematical shape — a worst-case ratio between an algorithm's cost and an optimum — but the source of the gap differs. In approximation algorithms, the optimum is knowable in principle but computationally intractable to find (the problem is NP-hard), so the ratio measures a computational shortfall. In competitive analysis, the online algorithm could compute the true optimum easily if it only knew the whole input — the ratio measures an informational shortfall caused by not seeing the future. Both frameworks use the same proof pattern (matching upper and lower bounds), which is why they are often taught side by side.
Why does the additive constant a matter in the definition of c-competitive?
Without it, a single unlucky short sequence could make a genuinely excellent algorithm look non-competitive, purely due to rounding or fixed startup costs that don't scale with the sequence length. For instance, an algorithm might incur a small fixed setup cost on any sequence, which would violate a strict `cost_ALG ≤ c · cost_OPT` bound when OPT is very small (even zero), even though the algorithm behaves ideally as sequences grow long. Allowing `cost_ALG ≤ c · OPT + a` captures the asymptotic worst-case behavior that actually matters, while still requiring the ratio `c` to hold uniformly as the input grows arbitrarily large.
Does a good competitive ratio guarantee good real-world performance?
Not necessarily, and this is the central honest tradeoff of the framework. Competitive ratios are worst-case guarantees constructed against a maximally adversarial input sequence, which real workloads rarely resemble. LRU's proven ratio of k looks alarming for large caches, yet LRU performs very well in practice because real access patterns exhibit temporal locality that the adversary's pathological construction deliberately ignores. Competitive analysis guarantees a floor on how bad things can get, not a prediction of typical behavior — production systems typically combine competitive guarantees with empirical benchmarking on realistic traces.
What is the oblivious adversary, and why does it matter so much for randomized bounds?
The oblivious adversary must commit to the entire input sequence in advance, without observing the algorithm's random coin flips as they occur — it can only reason about the algorithm's distribution over strategies. This is the standard model for proving that randomization helps, because it is precisely the constraint that prevents the adversary from tailoring each request to defeat the algorithm's specific realized choices. Stronger adversary models (adaptive-online, which sees past outcomes and adapts the next request; adaptive-offline, which sees everything and is charged against a fully-informed offline optimum) exist and generally yield weaker guarantees, so any stated competitive ratio for a randomized algorithm should specify which adversary model it assumes.
How does the ski-rental problem generalize beyond literal ski trips?
Ski rental is the cleanest instance of the general rent-or-buy (or explore-vs-commit) pattern: a recurring cost versus a one-time investment, under uncertainty about how long the recurring cost will be paid. It models caching a computed value versus recomputing it each time, provisioning a reserved cloud instance versus paying on-demand, migrating a codebase to new infrastructure versus continuing to patch the old one, and even deciding when to refactor code that is repeatedly causing small bugs. Whenever a system faces a "switch now, or keep paying incrementally" decision without knowing the remaining horizon, the break-even algorithm's 2-competitive guarantee (or its randomized e/(e−1) improvement) applies directly.
Can an online algorithm ever be 1-competitive, matching the offline optimum exactly?
Only in degenerate or highly structured cases — for most interesting problems, a competitive ratio strictly greater than 1 is unavoidable, and this is provable via an adversary argument, not just empirically observed. If a problem admits a 1-competitive online algorithm, it typically means the problem has enough structure (e.g., all decisions are forced, or future information doesn't actually change the optimal decision) that "online" and "offline" coincide. Ski rental and paging both have provable multiplicative lower bounds strictly above 1 for deterministic algorithms, which is precisely why competitive analysis is interesting: it quantifies an unavoidable cost of decision-making under uncertainty, not merely an artifact of a particular algorithm's design.
How do "algorithms with predictions" relate to classical competitive analysis?
This active research area augments the classical worst-case framework by giving the algorithm access to a (possibly wrong) machine-learned prediction about the future — e.g., predicted page-access frequency or predicted job size — and asks for algorithms that are simultaneously consistent (near-optimal when predictions are accurate) and robust (still competitive in the classical worst-case sense when predictions are arbitrarily bad). It directly extends the ski-rental and paging frameworks developed here: recent results give ski-rental and paging algorithms whose competitive ratio degrades gracefully and provably as prediction error grows, rather than falling back catastrophically, bridging classical worst-case theory with practical machine-learned forecasting.