Module contents
Lesson 25 of 33Advanced 95 min

Online algorithms and competitive analysis

Many decisions are made without knowing the future: cache eviction, when to buy rather than rent, or which server receives a request. Competitive analysis compares against an optimum that knows the future. Study deterministic and randomized ski rental, LRU paging and its k bound, randomized marking and H_k, Yao's minimax principle and an O(1) LRU cache.

After this lesson you can

  • Calculate competitive ratios and construct adversarial inputs.
  • Prove the ski-rental ratio 2 and derive the optimal randomized strategy.
  • Prove LRU is k-competitive and no deterministic algorithm improves it.
  • Apply Yao's principle to lower-bound randomized algorithms.
  • Implement an O(1) LRU cache and compare it with Belady on real traces.

Before you start

Motivation: decide without knowing the future

Every time your CPU reads a memory address, its L1 cache has a few nanoseconds to decide which line to evict if the needed one is absent. A CDN node decides what videos to keep on disk without knowing tomorrow’s requests. An LLM server such as vLLM keeps KV-cache blocks for computed prefixes on GPU to avoid recomputing them for later requests with the same beginning, and when memory fills evicts least-recently-used free blocks (see prefix caching). In all three, the decision is made now and its quality depends on requests not yet received.

This is not just about caches. Pay for a one-year reserved instance or continue hourly? Should a thread awaiting a lock spin or sleep, given a fixed sleep-and-wake cost? Which server receives a request now when future requests are unknown? Each has the same form: requests revealed one by one and irrevocable decisions made on arrival.

You know two ways to analyze operation sequences. Amortized analysis bounds total cost of any sequence without comparison. The streaming model limits memory, not information: the algorithm sees data in order but answers only at the end. Here information is limited and the yardstick differs: compare algorithm cost with an offline optimum knowing the entire sequence in advance. The worst-case ratio is the competitive ratio, developed through two canonical problems: ski rental and paging.

The online model and competitive ratio

An online minimization problem consists of requests σ=(σ1,…,σn)\sigma = (\sigma_1, \dots, \sigma_n) and state (cache contents, whether equipment has been bought). An online algorithm receives σt\sigma_t, must serve it using an action depending only on σ1,…,σt\sigma_1, \dots, \sigma_t, and pays a cost. Let ALG(σ)\mathrm{ALG}(\sigma) be total cost and OPT(σ)\mathrm{OPT}(\sigma) the minimum cost attainable by an algorithm knowing all of σ\sigma, the offline optimum.

Three comments. First, this is a relative worst-case bound: it does not say the algorithm is cheap, only that it is never much worse than the best possible on the same input. A sequence expensive for everyone, including OPT, does not penalize it. Second, additive constant α\alpha absorbs startup effects (the cache starts empty), but can trivialize bounded-cost problems; in ski rental, for example, reasonable cost is at most 2B2B, so strict competitiveness is used. Third, there is no computation-time assumption: OPT can be NP-hard to compute, and the online algorithm exponential. The measure is the price of not knowing, not inability to compute, distinguishing it from approximation ratio.

The definition describes a game. The designer picks the algorithm, then an adversary picks the sequence hurting it most. With a deterministic algorithm the adversary can simulate it and knows every response. With randomness, what the adversary sees matters:

  • Oblivious adversary. Knows the algorithm, including its coin distribution, but fixes the whole sequence before the coins are tossed. This is the model above and makes sense when requests come from the world, not an observer of decisions.
  • Adaptive online adversary. Constructs σt+1\sigma_{t+1} while seeing algorithm decisions through tt, but must also serve its own sequence online.
  • Adaptive offline adversary. Sees decisions while constructing the sequence and finally pays the offline optimum for that sequence.

The third is strong enough to nullify randomness: Ben-David, Borodin, Karp, Tardos and Wigderson (1994) proved that if a randomized algorithm is cc-competitive against adaptive offline adversaries, a deterministic cc-competitive algorithm exists. All randomization gains below are against oblivious adversaries.

Ski rental

You ski without knowing how many days: the season ends when snow runs out or you are injured, and you learn only that morning. Renting costs 1 per day; buying costs BB (an integer) and nothing afterward. If the season lasts DD days, offline optimum is obvious: OPT(D)=min⁡(D,B)\mathrm{OPT}(D) = \min(D, B). This is ski rental, prototype of rent-or-buy dilemmas: reserved instances, spinning or sleeping on locks, powering down or keeping disks on.

A deterministic algorithm receives no information beyond “the season continues,” so is described by one number: day kk on which it buys if still skiing (rent on days 1,…,k−11, \dots, k - 1 and buy at the start of day kk). Its cost is

ALGk(D)={Dsi D<k,k−1+Bsi D≥k.\mathrm{ALG}_k(D) = \begin{cases} D & \text{si } D < k, \\ k - 1 + B & \text{si } D \ge k. \end{cases}

The adversary sees one weakness: end the season on the day you buy, when you have paid rent and purchase without enjoying anything afterward.

InteractiveThe ski-rental game
Algorithm cost and optimum versus D010200B2B3BRatio ALG / OPT12worst: 1.90
  • algorithm cost
  • offline optimum
  • (2−1/B)⋅OPT(2 - 1/B)\cdot\mathrm{OPT}
  • cB⋅OPTc_B\cdot\mathrm{OPT}, optimal randomized
10
Strategy
10
10 days
Algorithm cost19.00
Optimum min⁡(D,B)\min(D, B)10
Ratio1.900
Worst ratio1.900 (D = 10)
Best deterministic1.900
Best randomized1.535
Limit e/(e−1)e/(e - 1)1.582
Buying on day BB guarantees 2−1/B=1.902 - 1/B = 1.90. The worst case is the season ending exactly on the purchase day.
Above, cost of your strategy (blue) and optimum min⁡(D,B)\min(D, B) (gray) versus season duration DD; middle, their ratio, with worst case circled red. Move purchase day kk and click ‘Adversary: worst ending’: where is the worst DD? Find kk minimizing the worst ratio. Switch to ‘Optimal random’: the ratio curve flattens at 1/(1−(1−1/B)B)1/(1 - (1 - 1/B)^B) and the third plot shows purchase probabilities by day. Compare uniform. Finally draw the day and enable ‘Adversary sees the coin’.
Proof

Upper bound with k=Bk = B: if D<BD < B the algorithm pays D=OPTD = \mathrm{OPT}; if D≥BD \ge B it pays 2B−12B - 1 and OPT pays BB, ratio 2−1/B2 - 1/B. Lower bound: the figure suggests the argument (the adversary ends the season on purchase day kk), completed in the final guided exercise.

∎

Randomize: make the adversary indifferent

Against an oblivious adversary a randomized strategy is a distribution over purchase day. The idea making it optimal comes from zero-sum games: if the adversary knows which DD hurts you most, it chooses that; the best defense makes every DD equally bad. The continuous version is cleaner: time is real, rental costs 1 per time unit and purchase occurs at time t∈[0,B]t \in [0, B] drawn with density pp.

Proof

For y≤By \le B, the algorithm pays t+Bt + B if buying at t<yt < y and yy if not yet bought:

E[ALG(y)]=∫0y(t+B) p(t) ⁣dt+y∫yBp(t) ⁣dt.\E[\mathrm{ALG}(y)] = \int_0^y (t + B)\,p(t)\dd t + y\int_y^B p(t)\dd t.

Require c yc\,y for every y∈[0,B]y \in [0, B]. Differentiating with respect to yy cancels terms ±y p(y)\pm y\,p(y), leaving B p(y)+∫yBp(t) ⁣dt=cB\,p(y) + \int_y^B p(t)\dd t = c. Differentiate again: B p′(y)−p(y)=0B\,p'(y) - p(y) = 0, so p(y)=Key/Bp(y) = K e^{y/B}. Normalization ∫0BKet/B ⁣dt=KB(e−1)=1\int_0^B K e^{t/B}\dd t = KB(e - 1) = 1 fixes KK, and evaluating the first derivative at y=0y = 0 gives c=B p(0)+1=1e−1+1=ee−1c = B\,p(0) + 1 = \frac{1}{e - 1} + 1 = \frac{e}{e - 1}. For y>By > B cost does not change (purchase is certain by then) and OPT=B\mathrm{OPT} = B, so ratio remains e/(e−1)e/(e - 1). In the discrete version, the same reasoning with differences gives E[ALG(D)]−E[ALG(D−1)]=B pD+P(comprar despueˊs de D)\E[\mathrm{ALG}(D)] - \E[\mathrm{ALG}(D - 1)] = B\,p_D + \Pr(\text{comprar después de } D); equating it to cc for every D≤BD \le B forces pD−1=pD(1−1/B)p_{D-1} = p_D(1 - 1/B), and normalization gives cBc_B.

∎

The figure shows two things. Density increases: the optimal strategy buys rather late but keeps early-purchase probability so a long season is not too expensive. And shape matters: uniform on [0,B][0, B] gives expected cost 2y−y2/(2B)2y - y^2/(2B), whose ratio tends to 2 as y→0y \to 0. Randomness alone does not help; the distribution equalizing all cases does. Is e/(e−1)e/(e - 1) best possible? Yes, as Yao’s principle will show.

A potential analysis: move to front

Before paging, a short example shows how competitive analysis and the potential method combine, and started the field. A linked list of mm elements receives access requests; accessing position ii costs ii, moving the accessed element forward is free and any other adjacent swap costs 1. Move to front (MTF) moves every accessed element to the head.

Proof

Let Φ\Phi count inversions between MTF’s and OPT’s lists: pairs {x,y}\{x, y\} in different orders. It starts at 0 and is never negative. On access to xx, let jj count elements before xx in both lists and ℓ\ell those before it in MTF but after it in OPT. MTF pays j+ℓ+1j + \ell + 1; moving xx to the head destroys ℓ\ell inversions with those elements and creates at most jj, so ΔΦ≤j−ℓ\Delta\Phi \le j - \ell. OPT pays at least j+1j + 1 for access; its free swaps can only remove inversions and each paid swap creates at most one, so if it makes PP paid swaps, ΔΦ\Delta\Phi rises by at most PP. MTF’s amortized step cost is j+ℓ+1+(j−ℓ)+P=2j+1+P≤2(j+1+P)−1j + \ell + 1 + (j - \ell) + P = 2j + 1 + P \le 2(j + 1 + P) - 1, less than twice OPT’s payment. Summing, final potential is nonnegative and initial potential 0.

∎

Potential measures distance between algorithm and optimum states and pays their cost difference. This idea reappears in splay trees, doing the same with trees instead of lists, and the still-open dynamic optimality conjecture.

Paging

The central competitive-analysis problem. Fast memory holds kk pages and slow memory the rest. Each request is a page; if fast memory contains it, a hit costs nothing; otherwise a page fault costs 1, brings it in and, if full, evicts another. The algorithm chooses only which page to evict. Assume demand paging (a page loads only on request); prefetching will soon be shown not to help. This is the external-memory model with block size 1 and no control over access order.

Offline optimum: farthest in the future

Proof

Count loads rather than faults and allow schedules loading unrequested pages. They gain nothing: every anticipatory load of qq can be delayed until the next request for qq (or removed if none) without increasing loads, so a demand schedule attains the minimum over all schedules.

Let SS be an optimal demand schedule agreeing with FF on its first ii requests. Construct another optimal S′S' agreeing with FF on its first i+1i + 1; iteration yields FF. If request i+1i + 1 is a hit or SS evicts what FF does, set S′=SS' = S. Otherwise let dd be the requested page, ee the one FF evicts and f≠ef \neq e the one SS evicts. Let S′S' evict ee then imitate SS. Caches differ only because SS has ee and S′S' has ff, until the first event below (if neither occurs, S′S' makes exactly SS’s loads):

  1. SS evicts ee to bring another page gg. S′S' evicts ff and brings gg: same loads and identical caches thereafter.
  2. ff is requested. SS faults and S′S' hits. If SS evicts ee to bring ff, caches equalize and S′S' has one fewer load. If it evicts another page hh, S′S' evicts hh and preloads ee: caches equalize with the same loads.

ee cannot be requested before ff: FF chose ee precisely because its next request was farthest away. In all cases S′S' makes no more loads than SS, agrees with FF at step i+1i + 1 and, after eliminating its preloads as above, still agrees.

∎

Belady is not online because it needs the future, but is the yardstick. It explains why results here concern ratios: ideal cache contents depend on requests the online algorithm has not seen.

LRU, FIFO and relatives

Classic online policies evict according to the past. LRU (least recently used) evicts the page with the oldest last use; FIFO the longest in cache, even if used frequently; LFU (least frequently used) the fewest accesses. CLOCK, used by many operating systems, cheaply approximates LRU with one use bit per page. The first three are the paging and LRU policies studied here.

InteractiveCache-policy race
Request trace and misses per policy (filled square = miss)page1234512345123451234512345123451234512345LRUFIFOLFUMarkingBeladyAfter request 40 (page 5)LRU2hace 33hace 24hace 15hace 0miss, evict 1FIFO2llegó 373llegó 384llegó 395llegó 40miss, evict 1LFU21×31×41×51×miss, evict 1Marking5marked2marked4marked3markedhitBelady3never4never5never2neverhit
40 of 40
  • LRU
  • FIFO
  • LFU
  • Marking
  • Belady
4
4
40
Requests
Misses (and multiple of Belady)
LRU40 (3.08×)
FIFO40 (3.08×)
LFU40 (3.08×)
Marking22 (1.69×)
Belady (optimal)13
Phases of kk distinct pages10
LRU bound k/(k−h+1)k/(k - h + 1)4.00
Marking bound 2Hk2H_k4.17
With k+1=5k + 1 = 5 pages in a loop, the requested page is always the one LRU and FIFO just evicted: they miss every access. Belady evicts the page used latest and misses once every kk requests.
Five caches serve the same trace in parallel. In each row, a filled square is a fault and a dot a hit; magenta lines separate phases of kk distinct pages used by the proofs. Below, each cache after the selected request, with each policy’s criterion: time since last use (LRU), arrival (FIFO), use count (LFU), whether marked (marking), and next request (Belady). Start with the k+1k + 1-page loop: how often does Belady fault? Try the scan that defeats LRU but not LFU, and uniform trace where they look similar. Lower hh to give Belady a smaller cache and enter your own trace under ‘Requests’.

The figure shows every deterministic policy’s weakness. With k+1k + 1 pages requested in a loop, LRU caches exactly the last kk and the requested page is the one missing: every access faults. Belady evicts the page returning latest and faults once every kk requests. Ratio kk is no LRU accident.

To analyze policies together, define phases: the first starts at the first request and each is the maximal segment with at most kk distinct pages; the next starts with distinct page number k+1k + 1. An algorithm is conservative if any request segment with at most kk distinct pages incurs at most kk faults. LRU is conservative: a page requested in such a segment stays among the kk most recently used until it ends. FIFO is too: if page xx faulted twice in the segment, FIFO must have evicted it between them, possible only when xx is the oldest page of a full cache, after loading k−1k - 1 other pages still cached plus the eviction-triggering page; with xx, the segment would have k+1k + 1 distinct pages. (Young, 1994, introduced conservative algorithms.)

Part 1 follows from two phase observations: a conservative algorithm faults at most kk times per phase, and OPT faults at least once on each segment from a phase’s second request to the next phase’s first. A guided exercise gives the full proof; resource augmentation generalizes it. Part 2 is the loop against any algorithm:

Proof

Let AA be deterministic and consider k+1k + 1 pages. Since the adversary can simulate AA, each step requests the sole one of k+1k + 1 pages missing from AA’s cache (after filling it with kk initial requests). Thus AA faults on every one of nn requests. To bound OPT use Belady: when it faults at time tt requesting pp and evicts qq, its cache contains every page except qq, and its next fault is the next request for qq. Since qq was the latest-returning of the kk cached pages before the fault, the other k−1k - 1 are requested first, so at least kk requests separate consecutive Belady faults. Therefore OPT≤n/k+k\mathrm{OPT} \le n/k + k, and if A(σ)≤c OPT(σ)+αA(\sigma) \le c\,\mathrm{OPT}(\sigma) + \alpha for every σ\sigma, with n→∞n \to \infty we get c≥kc \ge k.

∎

LFU is worse: it is not competitive at all. With k=2k = 2, request page aa a million times then alternate b,c,b,c,…b, c, b, c, \dots. LFU protects aa with a million accumulated uses and faults on each alternating request for a long time, while OPT evicts aa and faults no more. No constant bounds the ratio. In the lab a real matrix-multiplication trace shows it: with good loop order, LFU has almost 8 times Belady’s faults.

Randomness: the marking algorithm

Bound kk arises because the adversary knows which page is absent. If eviction is random, an oblivious adversary no longer knows.

Algorithm phases match the earlier kk-distinct-page phases: a marked page is never evicted, and marks clear exactly when distinct page number k+1k + 1 arrives. LRU is a deterministic marking algorithm (the least recently used page is never marked if any is unmarked); randomized marking changes only eviction choice. It is Las Vegas: requests are always served correctly; only cost is random.

Proof

Number phases 1,…,m1, \dots, m. A page of phase i≥2i \ge 2 is new if not requested in phase i−1i - 1 and old otherwise; let mim_i count new pages in phase ii (in the first, with empty cache, all are new: m1=km_1 = k).

OPT pays at least half the new pages. Phases i−1i - 1 and ii together request at least k+mik + m_i distinct pages, and at phase i−1i - 1 start OPT caches at most kk: it faults at least mim_i times in those phases. Summing over the ii pairs, whose phase pairs are disjoint, OPT≥∑i parmi\mathrm{OPT} \ge \sum_{i\text{ par}} m_i; summing odd pairs (with phase 1 alone) gives OPT≥∑i imparmi\mathrm{OPT} \ge \sum_{i\text{ impar}} m_i. Thus OPT≥12∑imi\mathrm{OPT} \ge \frac12\sum_i m_i.

Marking pays at most HkH_k per new page. At phase i≥2i \ge 2 start the cache holds exactly the kk pages of phase i−1i - 1, all unmarked. Each new page causes exactly one fault. For old pages use indicators: let XjX_j indicate whether the jj-th distinct old page requested in the phase faults on first request (later ones hit because it is marked). At that point k−j+1k - j + 1 old pages are unrequested. Marked pages occupy j−1+ℓj - 1 + \ell slots, where ℓ≤mi\ell \le m_i counts new pages requested so far, and the rest of cache, k−(j−1)−ℓk - (j - 1) - \ell slots, are unrequested old pages: exactly ℓ\ell are absent. Since the adversary is oblivious, sequence is independent of coins, and each eviction selects uniformly among unmarked pages; by symmetry the ℓ\ell missing form a uniform subset of unrequested old pages. Thus E[Xj]=ℓ/(k−j+1)≤mi/(k−j+1)\E[X_j] = \ell/(k - j + 1) \le m_i/(k - j + 1), and by linearity

E[fallos en la fase i]≤mi+∑j=1k−mimik−j+1=mi(1+Hk−Hmi)≤miHk.\E[\text{fallos en la fase } i] \le m_i + \sum_{j=1}^{k - m_i}\frac{m_i}{k - j + 1} = m_i\big(1 + H_k - H_{m_i}\big) \le m_i H_k.

Summing, E[MARK]≤Hk∑imi≤2Hk OPT\E[\mathrm{MARK}] \le H_k\sum_i m_i \le 2H_k\,\mathrm{OPT}.

∎

The improvement is huge: 2H64≈9.492H_{64} \approx 9.49 versus 64. Exact analysis (Achlioptas, Chrobak and Noga, 2000) gives 2Hk−12H_k - 1 for this algorithm, and more elaborate randomized algorithms attain exactly HkH_k, such as Partition (McGeoch and Sleator, 1991). In the figure’s k+1k + 1-page loop, marking averages about HkH_k faults per phase versus Belady’s one: on that trace the proof’s bound is exact because each phase has one new page.

Lower bounds: Yao’s principle

Can a randomized algorithm beat HkH_k? Proving not would require reasoning over all distributions over all algorithms. Yao’s principle replaces this with a manageable task: reason about one input distribution and deterministic algorithms.

Proof

Worst case is at least the average over QQ, and expectations can be interchanged: max⁡σEP[C]≥EQEP[C]=EPEQ[C]≥min⁡aEQ[C]\max_\sigma \E_P[C] \ge \E_Q\E_P[C] = \E_P\E_Q[C] \ge \min_a \E_Q[C]. For the competitive version, if EP[a(σ)]≤c′ OPT(σ)+α\E_P[a(\sigma)] \le c'\,\mathrm{OPT}(\sigma) + \alpha for all σ\sigma, average over QQ and use the inequality above to get c EQ[OPT]≤c′ EQ[OPT]+αc\,\E_Q[\mathrm{OPT}] \le c'\,\E_Q[\mathrm{OPT}] + \alpha; divide and let EQ[OPT]\E_Q[\mathrm{OPT}] grow to obtain c′≥cc' \ge c.

∎

The inequality is the easy half of an equality. The game between designer (rows, mixed strategies PP) and adversary (columns, mixed strategies QQ) is a zero-sum minimax problem, and von Neumann’s theorem makes the best randomized algorithm against worst case cost exactly the same as the best deterministic one against the worst input distribution. Yao’s minimax principle says one bad distribution suffices for a lower bound, and duality guarantees the optimal bound can always be obtained this way.

Proof

Take k+1k + 1 pages and independent uniform requests over them of length nn. For a deterministic algorithm, request tt is independent of its current cache, holding at most kk of k+1k + 1 pages: it faults with probability at least 1/(k+1)1/(k + 1), and E[A]≥n/(k+1)\E[A] \ge n/(k + 1). For OPT use Belady: if it faults at tt requesting pp and evicts qq, its next fault is the next request for qq, before which all other cached pages are requested. Between consecutive faults all kk distinct pages of pp therefore appear, and waiting for kk specific coupons among k+1k + 1 equiprobable ones takes ∑i=1kk+1i=(k+1)Hk\sum_{i=1}^{k}\frac{k + 1}{i} = (k + 1)H_k requests on average (coupon collector). By the renewal-process law of large numbers, E[OPT]≤n/((k+1)Hk)+o(n)\E[\mathrm{OPT}] \le n/((k + 1)H_k) + o(n), and the ratio of expectations tends to at least HkH_k. Yao concludes.

∎

The same argument proves the exponential strategy optimal for ski rental: a season-duration distribution exists against which no deterministic purchase day beats cBc_B in the discrete version (or e/(e−1)e/(e - 1) continuous). The lab computes it by solving the game as a linear program; both optimal strategies, designer and adversary, emerge from primal and dual.

Resource augmentation

Result kk compares LRU to an optimum with the same cache. Sleator and Tarjan observed that giving the online algorithm a little more memory removes pessimism.

Proof

Divide the sequence into phases of kk distinct pages, mm total. LRU faults at most kk times per phase because it is conservative: LRUk≤k m\mathrm{LRU}_k \le k\,m. Let pp be phase i<mi < m’s first page and consider the segment from phase ii’s second request to phase i+1i + 1’s first. It contains the k−1k - 1 pages of phase ii other than pp and the opening page of phase i+1i + 1, which differs from all of them: at least kk pages distinct from pp. At the segment’s start OPT has just served pp, so holds pp and at most h−1h - 1 other pages; at least k−(h−1)k - (h - 1) of those kk pages are absent and each causes a fault within the segment. Segments from different phases are disjoint, so OPTh≥(k−h+1)(m−1)\mathrm{OPT}_h \ge (k - h + 1)(m - 1). Combining, LRUk≤k m≤kk−h+1OPTh+k\mathrm{LRU}_k \le k\,m \le \frac{k}{k - h + 1}\mathrm{OPT}_h + k.

∎

With h=kh = k this is exactly kk-competitiveness. In the race, lower hh on the k+1k + 1-page loop and watch LRU and Belady curves approach; in the lab, with long traces, k=8k = 8 and h=4h = 4, measured ratio is 1.601.60, exactly bound 8/58/5. This is an early beyond-worst-case analysis: doubling cache is inexpensive in hardware and turns a useless guarantee into a very good one.

An O(1) LRU cache

Implementing LRU with a recency-ordered list is natural and slow: accessing a page requires finding and moving it to the end, and list.remove traverses the list, O(k)\bigO(k) per access. The correct structure combines two familiar pieces. A hash table maps each key to its node in expected O(1)\bigO(1); a doubly linked list maintains recency and removes a node given its pointer or inserts it at the head by rewriting a fixed number of pointers. Two sentinel nodes at the ends eliminate empty-list special cases. This is the O(1) LRU cache.

InteractiveInside an LRU cache
Hash table: key X goes to bucket code(X) mod 801234567headtailmost recentA: step 1 of 3, lookup (miss)least recent
access 1 of 9
ABCDAECFB
4
Access a key
Access1: A, miss
Micro-step1 of 3
Pointers rewritten (step / access)0 / 0
Hash table operations1
list.remove would traverse· (miss)
Hits / misses0 / 1
Access A: the hash table does not contain it. This is a miss and it must be fetched.
Above, the hash table: each key is in its code modulo 8 bucket and points to its node. Below, the doubly linked list between head (most recent) and tail (least recent) sentinels. Advance micro-step by micro-step: a hit is a lookup, unlink (2 pointers) and link at head (4); a fault with full cache evicts the node before the tail and deletes its key from the table, so each node stores its key. Click letters to access them and increase capacity: pointers and lookups per access stay fixed; the work of ‘list.remove’ does not.

Two details matter in any implementation. The node stores its key because evicting the last node must also delete it from the table, and only the node is available. And O(1)\bigO(1) cost has two qualifications: list operations are worst-case O(1)\bigO(1), but hash-table operations are expected-time, and occasional resizing makes cost also amortized.

Lab 1: cache-policy simulator

Start with the figure’s structure from scratch, checked against OrderedDict and measured against list.remove.

[ ]LRU cache with dictionary and doubly linked listBrowser
import random, time
from collections import OrderedDict

class _Nodo:
    __slots__ = ("clave", "valor", "prev", "next")
    def __init__(self, clave=None, valor=None):
        self.clave, self.valor = clave, valor
        self.prev = self.next = None

class LRUCache:
    """Caché LRU: diccionario clave -> nodo y lista doblemente enlazada con centinelas."""
    def __init__(self, capacidad):
        self.cap = capacidad
        self.tabla = {}
        self.cabeza, self.cola = _Nodo(), _Nodo()      # centinelas: nunca hay que comprobar None
        self.cabeza.next, self.cola.prev = self.cola, self.cabeza

    def _desenganchar(self, nodo):                     # 2 punteros
        nodo.prev.next, nodo.next.prev = nodo.next, nodo.prev

    def _al_frente(self, nodo):                        # 4 punteros
        nodo.prev, nodo.next = self.cabeza, self.cabeza.next
        self.cabeza.next.prev = nodo
        self.cabeza.next = nodo

    def get(self, clave, defecto=None):
        nodo = self.tabla.get(clave)
        if nodo is None:
            return defecto
        self._desenganchar(nodo)
        self._al_frente(nodo)
        return nodo.valor

    def put(self, clave, valor):
        """Inserta o actualiza; devuelve la clave desalojada (o None)."""
        nodo = self.tabla.get(clave)
        if nodo is not None:
            nodo.valor = valor
            self._desenganchar(nodo)
            self._al_frente(nodo)
            return None
        desalojada = None
        if len(self.tabla) == self.cap:
            viejo = self.cola.prev
            self._desenganchar(viejo)
            del self.tabla[viejo.clave]                # por eso el nodo guarda su clave
            desalojada = viejo.clave
        nodo = _Nodo(clave, valor)
        self.tabla[clave] = nodo
        self._al_frente(nodo)
        return desalojada

    def claves(self):
        """De la más reciente a la menos reciente."""
        out, n = [], self.cabeza.next
        while n is not self.cola:
            out.append(n.clave)
            n = n.next
        return out

# comprobación contra OrderedDict en 20000 operaciones aleatorias
random.seed(0)
mia, ref = LRUCache(8), OrderedDict()
for _ in range(20000):
    c = random.randrange(20)
    if random.random() < 0.5:
        r2 = ref.get(c)
        if c in ref:
            ref.move_to_end(c)
        assert mia.get(c) == r2
    else:
        mia.put(c, c * c)
        ref[c] = c * c
        ref.move_to_end(c)
        if len(ref) > 8:
            ref.popitem(last=False)
    assert mia.claves() == list(reversed(ref))
print("20000 operaciones: idéntica a OrderedDict")

class LRUConLista:
    """La versión ingenua: una lista con la más reciente al final y list.remove."""
    def __init__(self, capacidad):
        self.cap, self.orden, self.datos = capacidad, [], {}
    def get(self, clave, defecto=None):
        if clave not in self.datos:
            return defecto
        self.orden.remove(clave)                       # recorre la lista: O(k)
        self.orden.append(clave)
        return self.datos[clave]
    def put(self, clave, valor):
        if clave in self.datos:
            self.orden.remove(clave)
        elif len(self.datos) == self.cap:
            del self.datos[self.orden.pop(0)]          # pop(0) también es O(k)
        self.orden.append(clave)
        self.datos[clave] = valor

def microsegundos(Cache, k, m=4000):
    c = Cache(k)
    for i in range(k):
        c.put(i, i)
    rnd = random.Random(1)
    claves = [rnd.randrange(k) for _ in range(m)]
    t0 = time.perf_counter()
    for x in claves:
        c.get(x)
    return 1e6 * (time.perf_counter() - t0) / m

print(f"{'k':>6} {'dict + lista enlazada':>22} {'list.remove':>12}   (µs por acceso)")
for k in (10, 1000, 10000):
    print(f"{k:>6} {microsegundos(LRUCache, k):>22.2f} {microsegundos(LRUConLista, k):>12.2f}")

The linked-list column stays fixed when kk increases a thousandfold; list.remove grows linearly. With k=10k = 10 they cost the same, explaining why small tests miss the mistake.

Now five policies. Simulation only needs fault counts, so LRU uses OrderedDict (internally a dictionary with doubly linked list) and Belady a heap of next uses.

[ ]Five eviction policiesBrowser
import heapq, random
from collections import OrderedDict, deque

def fallos_lru(traza, k):
    cache, f = OrderedDict(), 0
    for p in traza:
        if p in cache:
            cache.move_to_end(p)
        else:
            f += 1
            if len(cache) == k:
                cache.popitem(last=False)
            cache[p] = True
    return f

def fallos_fifo(traza, k):
    cache, cola, f = set(), deque(), 0
    for p in traza:
        if p not in cache:
            f += 1
            if len(cache) == k:
                cache.discard(cola.popleft())
            cache.add(p)
            cola.append(p)
    return f

def fallos_lfu(traza, k):
    """Frecuencia mientras la página está en caché; a igualdad, la usada hace más tiempo."""
    freq, ultimo, f = {}, {}, 0
    for t, p in enumerate(traza):
        if p not in freq:
            f += 1
            if len(freq) == k:
                del freq[min(freq, key=lambda q: (freq[q], ultimo[q]))]
            freq[p] = 0
        freq[p] += 1
        ultimo[p] = t
    return f

def fallos_marcado(traza, k, semilla=0):
    rnd = random.Random(semilla)
    cache, marcadas, f = set(), set(), 0
    for p in traza:
        if p not in cache:
            f += 1
            if len(cache) == k:
                if len(marcadas) == k:              # todas marcadas: empieza una fase
                    marcadas.clear()
                cache.remove(rnd.choice(sorted(cache - marcadas)))
            cache.add(p)
        marcadas.add(p)
    return f

def fallos_belady(traza, k):
    """El más lejano en el futuro, en O(n log n) con un montículo perezoso."""
    n = len(traza)
    prox, visto = [0] * n, {}
    for t in range(n - 1, -1, -1):
        prox[t] = visto.get(traza[t], n + t)        # n + t: «no vuelve», con desempate estable
        visto[traza[t]] = t
    en_cache, heap, f = {}, [], 0                    # en_cache[p] = próximo uso vigente de p
    for t, p in enumerate(traza):
        if p not in en_cache:
            f += 1
            if len(en_cache) == k:
                while True:                          # descarta entradas caducadas
                    nu, q = heapq.heappop(heap)
                    if en_cache.get(q) == -nu:
                        del en_cache[q]
                        break
        en_cache[p] = prox[t]
        heapq.heappush(heap, (-prox[t], p))
    return f

POLITICAS = {"LRU": fallos_lru, "FIFO": fallos_fifo, "LFU": fallos_lfu,
             "marcado": fallos_marcado, "Belady": fallos_belady}

s = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
for k in (3, 4):
    print(f"k = {k}:", {nombre: f(s, k) for nombre, f in POLITICAS.items() if nombre != "marcado"})

The short trace is Belady’s anomaly: FIFO faults 9 times with 3 frames and 10 with 4. More memory, more faults. LRU and Belady cannot suffer it because cache contents with kk frames are always contained in those with k+1k + 1 (stack algorithms); FIFO lacks that property.

The main experiment compares five policies on synthetic traces and one from a real program: memory pages read from A\mat{A} and B\mat{B} by C=AB\mat{C} = \mat{A}\mat{B} matrix multiplication of 16×1616\times 16 row-major doubles, with 4 doubles per page and two loop orders.

[ ]Policy race on six tracesBrowser
import random

def traza_bucle(n, k):
    return [t % (k + 1) for t in range(n)]

def traza_zipf(n, paginas, s=1.0, semilla=0):
    rnd = random.Random(semilla)
    return rnd.choices(range(paginas), weights=[1 / (i + 1) ** s for i in range(paginas)], k=n)

def traza_escaneo(n, k, semilla=0):
    rnd, out, nueva = random.Random(semilla), [], 10**6
    while len(out) < n:
        out += [rnd.randrange(k - 1) for _ in range(2 * k)]   # conjunto caliente de k - 1 páginas
        out += list(range(nueva, nueva + k))                  # escaneo de k páginas que no vuelven
        nueva += k
    return out[:n]

def traza_uniforme(n, paginas, semilla=0):
    rnd = random.Random(semilla)
    return [rnd.randrange(paginas) for _ in range(n)]

def traza_matmul(N, pagina, orden):
    """Páginas de A y B que lee C = A B con N x N doubles por filas y `pagina` doubles por página."""
    pag = lambda m, i, j: (m, (i * N + j) // pagina)
    out = []
    for i in range(N):
        for u in range(N):
            for v in range(N):
                kk, j = (v, u) if orden == "ijk" else (u, v)  # ijk: el bucle interno recorre B por columnas
                out += [pag("A", i, kk), pag("B", kk, j)]
    return out

k, n = 8, 4000
trazas = {
    "bucle de k+1": traza_bucle(n, k),
    "Zipf, 64 páginas": traza_zipf(n, 64),
    "caliente + escaneos": traza_escaneo(n, k),
    "uniforme, 16 págs.": traza_uniforme(n, 16),
    "matmul ijk": traza_matmul(16, 4, "ijk"),
    "matmul ikj": traza_matmul(16, 4, "ikj"),
}
print(f"k = {k}. Fallos y, entre paréntesis, cociente con Belady\n")
print(f"{'traza':20s}{'accesos':>8}" + "".join(f"{p:>14s}" for p in POLITICAS))
for nombre, tr in trazas.items():
    res = {p: f(tr, k) for p, f in POLITICAS.items()}
    print(f"{nombre:20s}{len(tr):>8}" + "".join(f"{v:>7d} ({v / res['Belady']:4.2f})" for v in res.values()))
H8 = sum(1 / i for i in range(1, k + 1))
print(f"\ncotas del peor caso: LRU y FIFO {k}, marcado 2H_k = {2 * H8:.2f}")

The table summarizes the lesson. On the loop, LRU, FIFO and LFU fault on all 4000 requests, 7.897.89 times Belady (almost bound k=8k = 8), and marking stays at 2.702.70, nearly H8=2.72H_8 = 2.72. With scans, LFU ties Belady and LRU pays 1.81.8 times more. On the uniform trace all online policies are near 2: structureless traces do not distinguish them. In matrix multiplication, ikj order, traversing B\mat{B} row-wise, cuts LRU faults from 5120 to 1088, while LFU collapses at 7.757.75 times optimum: A\mat{A} pages accumulate uses and LFU clings to them after they stop being used. Loop order matters more than policy, the topic of external memory.

Now check three theoretical bounds: Yao with uniform requests over k+1k + 1 pages, marking on the loop, and resource augmentation.

[ ]Measuring H_k and k/(k - h + 1) boundsBrowser
H = lambda k: sum(1 / i for i in range(1, k + 1))

print("Peticiones uniformes sobre k + 1 páginas, n = 20000")
print(f"{'k':>3} {'LRU/n':>8} {'1/(k+1)':>8} {'Belady/n':>9} {'1/((k+1)H_k)':>13} {'LRU/Belady':>11} {'H_k':>6}")
for k in (2, 4, 8, 16):
    tr = traza_uniforme(20000, k + 1, semilla=k)
    lru, opt = fallos_lru(tr, k), fallos_belady(tr, k)
    print(f"{k:>3} {lru / 20000:>8.4f} {1 / (k + 1):>8.4f} {opt / 20000:>9.4f} {1 / ((k + 1) * H(k)):>13.4f} {lru / opt:>11.2f} {H(k):>6.2f}")

print("\nMarcado aleatorio en el bucle de k + 1 páginas (n = 8000, media de 10 semillas)")
for k in (2, 4, 8, 16):
    tr = traza_bucle(8000, k)
    m = sum(fallos_marcado(tr, k, s) for s in range(10)) / 10
    print(f"k = {k:>2}: marcado / Belady = {m / fallos_belady(tr, k):.2f}   H_k = {H(k):.2f}   2H_k = {2 * H(k):.2f}")

print("\nAumento de recursos: LRU con caché k en su traza adversaria, Belady con caché h")
for k, h in ((8, 8), (8, 6), (8, 4), (16, 8)):
    tr = traza_bucle(4000, k)
    print(f"k = {k:>2}, h = {h}: LRU / Belady = {fallos_lru(tr, k) / fallos_belady(tr, h):5.2f}   cota k/(k-h+1) = {k / (k - h + 1):.2f}")

With uniform requests, LRU faults on fraction 1/(k+1)1/(k + 1), like any deterministic algorithm, and Belady on 1/((k+1)Hk)1/((k + 1)H_k) as coupon collection predicts: ratio approaches HkH_k, Yao’s lower bound. Marking on the loop also approaches HkH_k (with k=16k = 16 convergence is slower because kk startup faults weigh more). Resource augmentation reaches bound k/(k−h+1)k/(k - h + 1): the loop is worst case there too.

Lab 2: rent or buy

[ ]Deterministic and randomized strategiesBrowser
import numpy as np

def coste(k, D, B):
    """Alquila los días 1..k-1 y compra al empezar el día k."""
    return D if D < k else k - 1 + B

def peor_cociente(k, B, Dmax=1000):
    return max(coste(k, D, B) / min(D, B) for D in range(1, Dmax + 1))

B = 10
print("Deterministas, B = 10:")
for k in (1, 5, 9, 10, 11, 15, 20):
    print(f"  comprar el día {k:>2}: peor cociente {peor_cociente(k, B):.3f}")
print(f"  2 - 1/B = {2 - 1 / B}")

def dist_optima(B):
    c = 1 / (1 - (1 - 1 / B) ** B)
    return c, np.array([(c / B) * (1 - 1 / B) ** (B - i) for i in range(1, B + 1)])

c, p = dist_optima(B)
dias = np.arange(1, B + 1)
esperado = lambda p, D: sum(pi * coste(i, D, B) for i, pi in zip(dias, p))
print(f"\nAleatorizada óptima, B = 10: c_B = {c:.4f}, suma de p = {p.sum():.12f}")
print("  E[ALG]/OPT para D = 1..15:", np.round([esperado(p, D) / min(D, B) for D in range(1, 16)], 4))
u = np.full(B, 1 / B)
print("  uniforme, E[ALG]/OPT para D = 1..5:", np.round([esperado(u, D) / min(D, B) for D in range(1, 6)], 3))

# versión continua: comprar en T con densidad e^(t/B) / (B (e - 1)) en [0, B], muestreada por inversión
rng = np.random.default_rng(0)
Bc = 1.0
T = Bc * np.log1p(rng.random(400_000) * (np.e - 1))
print(f"\nContinua (Monte Carlo, 400 000 muestras): e/(e-1) = {np.e / (np.e - 1):.4f}")
for y in (0.1, 0.3, 0.6, 1.0, 2.0):
    alg = np.where(T < y, T + Bc, y).mean()
    print(f"  temporada y = {y}: E[ALG]/OPT = {alg / min(y, Bc):.4f}")

Worst deterministic ratio is V-shaped with minimum 1.91.9 at k=Bk = B; optimal distribution gives 1.53531.5353 for all durations simultaneously, and uniform starts at 1.91.9 with D=1D = 1. To see cBc_B is best possible, solve the whole game. Rows are purchase days k=1,…,6B+1k = 1, \dots, 6B + 1 (the last acts as “never buy” within the horizon), columns durations D=1,…,6BD = 1, \dots, 6B, and entry ratio ALGk(D)/OPT(D)\mathrm{ALG}_k(D)/\mathrm{OPT}(D). The designer minimizes the column maximum using a mixed strategy, a linear program, and the dual gives the adversary’s mixed strategy.

[ ]The game as a linear program: minimax and YaoBrowser
import numpy as np
from scipy.optimize import linprog

B, N = 10, 60
K, Ds = np.arange(1, N + 2), np.arange(1, N + 1)
M = np.array([[coste(k, D, B) / min(D, B) for D in Ds] for k in K])   # filas: algoritmo; columnas: entrada
nk, nd = M.shape

# diseñador: min v  sujeto a  p^T M[:, D] <= v para toda D,  p >= 0,  sum p = 1
r = linprog(np.r_[np.zeros(nk), 1], A_ub=np.c_[M.T, -np.ones(nd)], b_ub=np.zeros(nd),
            A_eq=[np.r_[np.ones(nk), 0]], b_eq=[1], bounds=[(0, None)] * nk + [(None, None)], method="highs")
p = r.x[:-1]
print(f"valor del juego (diseñador): {r.x[-1]:.6f}   c_B = {1 / (1 - 0.9**10):.6f}")
print("días con probabilidad > 0:", K[p > 1e-9])
print("p del LP:     ", np.round(p[:B], 4))
print("p de la fórmula:", np.round(dist_optima(B)[1], 4))

# adversario: max w  sujeto a  M[k, :] q >= w para todo k,  q >= 0,  sum q = 1
r2 = linprog(np.r_[np.zeros(nd), -1], A_ub=np.c_[-M, np.ones(nk)], b_ub=np.zeros(nk),
             A_eq=[np.r_[np.ones(nd), 0]], b_eq=[1], bounds=[(0, None)] * nd + [(None, None)], method="highs")
q = r2.x[:-1]
print(f"\nvalor del juego (adversario): {-r2.fun:.6f}")
print("distribución de la duración:", {int(D): round(float(v), 4) for D, v in zip(Ds, q) if v > 1e-9})
print(f"Yao: mejor determinista contra q -> {(M @ q).min():.6f}, alcanzado por los días {K[np.isclose(M @ q, (M @ q).min())][:12]}")

Both optimal strategies emerge from primal and dual with the same value. The designer’s matches the exponential formula. The adversary’s is a duration distribution against which every deterministic purchase day has expected ratio at least cBc_B: exactly Yao’s certificate. Here the bound is on expectation of the ratio EQ[ALG/OPT]\E_Q[\mathrm{ALG}/\mathrm{OPT}] rather than ratio of expectations; since OPT\mathrm{OPT} is fixed per column, both forms are equivalent by reweighting QQ by 1/OPT(D)1/\mathrm{OPT}(D). The adversary distribution is not unique (the LP returns one of many), but its value is.

The professional version

Python provides two ready-made pieces. functools.lru_cache memoizes a function with LRU eviction (CPython implements it in C over a dictionary and circular doubly linked list), and OrderedDict offers move_to_end and popitem(last=False) in O(1)\bigO(1), enough for an LRU cache in ten lines. Check that lru_cache makes exactly our LRU faults:

[ ]functools.lru_cache and OrderedDictBrowser
from functools import lru_cache
from collections import OrderedDict

traza = traza_zipf(4000, 64, semilla=3)
for k in (4, 8, 16):
    @lru_cache(maxsize=k)
    def pagina(p):
        return p                     # «traer la página»: solo se ejecuta en un fallo
    for p in traza:
        pagina(p)
    info = pagina.cache_info()
    print(f"k = {k:>2}: lru_cache {info.misses} fallos, {info.hits} aciertos;  fallos_lru = {fallos_lru(traza, k)}")

class LRU(OrderedDict):
    """Caché LRU sobre OrderedDict: get y put en O(1)."""
    def __init__(self, k):
        super().__init__()
        self.k = k
    def get(self, clave, defecto=None):
        if clave not in self:
            return defecto
        self.move_to_end(clave)
        return self[clave]
    def put(self, clave, valor):
        self[clave] = valor
        self.move_to_end(clave)
        if len(self) > self.k:
            self.popitem(last=False)

c = LRU(2)
c.put("a", 1); c.put("b", 2); c.get("a"); c.put("c", 3)
print("\nclaves tras a, b, get(a), c con k = 2:", list(c))

Outside Python, real caches are seldom exact LRU. CPUs use cheap approximations (tree-bit pseudo-LRU per set) because maintaining exact hardware order is expensive; operating systems use CLOCK and variants; databases and CDNs add scan resistance (2Q, ARC, LRU-K), exactly the scan-trace weakness shown. In high-performance multithreaded caches the doubly linked list is a bottleneck because every hit modifies it, so CLOCK or sampling is used (Redis, for example, evicts the oldest-used key among a small random sample).

Toward the frontier: algorithms with predictions

Competitive analysis is pessimistic because it assumes no future knowledge. In practice a learned model can predict it reasonably well: season duration or when a page is next requested. Algorithms with predictions seek both consistency (with perfect prediction, ratio approaches 1) and robustness (with arbitrarily poor prediction, ratio remains bounded comparably to the best algorithm without predictions).

For ski rental, Purohit, Svitkina and Kumar (NeurIPS 2018) propose, with confidence parameter λ∈(0,1)\lambda \in (0, 1) and predicted duration yy: if y≥By \ge B buy at the start of day ⌈λB⌉\lceil\lambda B\rceil; if y<By < B buy at the start of day ⌈B/λ⌉\lceil B/\lambda\rceil. They prove ratio at most min⁡{1+λλ, (1+λ)+η(1−λ)OPT}\min\big\{\frac{1 + \lambda}{\lambda},\ (1 + \lambda) + \frac{\eta}{(1 - \lambda)\mathrm{OPT}}\big\}, with prediction error η=∣y−D∣\eta = \abs{y - D}: (1+λ)(1 + \lambda)-consistent and (1+1/λ)(1 + 1/\lambda)-robust. Small λ\lambda means high trust in the model; as λ\lambda approaches 1, both purchase days tend to BB and recover the classical prediction-ignoring strategy. For paging, Lykouris and Vassilvitskii (ICML 2018) modify marking to use predicted next use of each page: its ratio improves as prediction error falls and never exceeds O(log⁡k)\bigO(\log k), marking without predictions; blindly following an oracle can instead be very bad even when mean error is small.

The connection to machine learning goes further. Online learning and bandits compare with the best fixed expert in hindsight rather than offline optimum, bounding regret, a difference rather than a ratio. It is the same adversarial game with a different yardstick.

Common mistakes

Exercises

ProofDeterministic ski rental
Prove: In discrete ski rental with purchase price BB, buying at the start of day BB is strictly (2−1/B)(2 - 1/B)-competitive, and no deterministic algorithm has a smaller strict ratio.
0
A deterministic algorithm is described by purchase day kk if still skiing; with DD season days it pays DD if D<kD < k and k−1+Bk - 1 + B if D≥kD \ge k. Optimum pays min⁡(D,B)\min(D, B).

Step 1 of 3. How do you bound the ratio of strategy k=Bk = B?

ProofLRU is k-competitive
Prove: For every sequence σ\sigma, LRU(σ)≤k⋅OPT(σ)+k\mathrm{LRU}(\sigma) \le k\cdot\mathrm{OPT}(\sigma) + k, where both have cache kk and start with the same contents.
0
Divide σ\sigma into phases: each is the maximal segment with at most kk distinct pages and the next starts with distinct page number k+1k + 1. Let there be mm phases.

Step 1 of 3. How often can LRU fault in a phase?

NumericBounds with 64 pages
With a cache of k=64k = 64 pages, how many times larger is LRU’s competitive bound kk than randomized marking’s 2Hk2H_k?
NumericBelady by hand
With an initially empty k=3k = 3-page cache and sequence 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5, how many faults does Belady’s algorithm make?
NumericRandomized ratio with B = 4
In discrete ski rental with B=4B = 4, what is the optimal randomized strategy’s competitive ratio against an oblivious adversary?
NumericDouble the cache
LRU has cache k=16k = 16 pages and is compared to offline optimum with cache h=8h = 8. What factor does the resource-augmentation bound give?
QuizAn adversary seeing the coins
An attacker measures access times and always knows which pages randomized marking has cached, choosing the next request accordingly. Does guarantee 2Hk2H_k still hold?
QuizMore cache, more faults?
Which policies can fault more with a cache of k+1k + 1 pages than with kk on the same sequence?
CodeAn O(1) LRU cache
The starter code is a correct but slow LRU cache: list.remove and pop(0) traverse the list on each access. Rewrite it so get(clave) (returns the value or None and marks the key most recent) and put(clave, valor) (inserts or updates; if full, evicts the least recent) perform a constant number of operations. You may use a dictionary with your own doubly linked list, or OrderedDict. Tests check behavior and count key comparisons per operation with k=500k = 500.
class LRU:
  """Caché LRU de capacidad k. Funciona, pero cada acceso cuesta O(k): arréglalo."""
  def __init__(self, k):
      self.k = k
      self.orden = []          # claves, de la menos a la más reciente
      self.datos = {}

  def get(self, clave):
      """Devuelve el valor (o None si no está) y marca la clave como la más reciente."""
      if clave not in self.datos:
          return None
      self.orden.remove(clave)
      self.orden.append(clave)
      return self.datos[clave]

  def put(self, clave, valor):
      """Inserta o actualiza; si no cabe, desaloja la menos reciente."""
      if clave in self.datos:
          self.orden.remove(clave)
      elif len(self.datos) == self.k:
          del self.datos[self.orden.pop(0)]
      self.orden.append(clave)
      self.datos[clave] = valor

  def __len__(self):
      return len(self.datos)
Shift+Enter to run

Summary

Key idea
Competitive analysis measures the price of not knowing the future: on each input compare an online algorithm’s cost with the optimum that knows it fully, and seek the worst ratio against an adversary.
  • An algorithm is cc-competitive if ALG(σ)≤c OPT(σ)+α\mathrm{ALG}(\sigma) \le c\,\mathrm{OPT}(\sigma) + \alpha for every σ\sigma. With randomness it matters what the adversary sees: gains are against an oblivious adversary and disappear against an adaptive offline one.
  • In ski rental, buying on day BB gives 2−1/B2 - 1/B, the deterministic optimum; buying at a time with density ∝et/B\propto e^{t/B} equalizes ratios across durations and gives e/(e−1)≈1.58e/(e - 1) \approx 1.58, also optimal.
  • In paging, Belady (farthest in future) is offline optimum; LRU, FIFO and all conservative algorithms are kk-competitive and no deterministic algorithm improves it. LFU is not competitive.
  • Randomized marking is 2Hk2H_k-competitive, and Yao’s principle with uniform requests over k+1k + 1 pages shows no randomized algorithm beats HkH_k. Yao is the easy half of von Neumann’s minimax theorem.
  • With cache kk versus an optimum with cache hh, LRU is k/(k−h+1)k/(k - h + 1)-competitive: twice the memory gives a guarantee below 2.
  • An LRU cache is implemented in O(1)\bigO(1) with a hash table and doubly linked list with sentinels (or OrderedDict and functools.lru_cache), never with list.remove.