Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

8. Greedy algorithms: exchange arguments, optimal caching and Bélády’s anomaly

School of Engineering, Nazarbayev University

A greedy algorithm takes the locally most attractive choice, never backtracks, and is usually a few lines of code. Sometimes, as in earliest-finish-time interval scheduling and Bélády’s furthest-in-future cache eviction, the greedy choice is provably optimal. Other plausible greedy rules fail, and in Bélády’s FIFO anomaly (Bélády, Nelson & Shedler 1969) more memory (4 page frames instead of 3) gives more cache misses. This lecture covers Mental Move #17, Prove Greedy via an Exchange Argument (or Break It): testing greedy_heuristic_search.interval_scheduling_greedy against three other plausible rules (including an 11-interval trap for fewest conflicts), comparing offline optimal caching with greedy_heuristic_search.belady_optimal_cache, reproducing the FIFO anomaly and checking why LRU cannot show it, and building an automated counterexample search.

Learning objectives

  1. Prove global optimality of Earliest-Finish-Time (greedy_heuristic_search.interval_scheduling_greedy) via the Stay-Ahead / Exchange Argument, and construct minimal counterexamples breaking Earliest-Start, Shortest-Duration, and Fewest-Conflicts.

  2. Evaluate Bélády’s Furthest-in-Future offline optimal cache (greedy_heuristic_search.belady_optimal_cache) as a tight lower bound on page misses for online LRU and FIFO across realistic Zipfian and cyclic traces.

  3. Reproduce Bélády’s (1969) FIFO Anomaly (MFIFO(k=4)>MFIFO(k=3)M_{\mathrm{FIFO}}(k=4) > M_{\mathrm{FIFO}}(k=3)) and prove why LRU’s Stack Inclusion Property (Ck(t)⊆Ck+1(t)\mathcal{C}_k(t) \subseteq \mathcal{C}_{k+1}(t)) guarantees monotone miss rates.

  4. Automate counterexample discovery for non-canonical greedy coin change and implement O(Nlog⁡N)\mathcal{O}(N \log N) weighted interval scheduling DP where unit-weight greedy breaks down.

Time: about 60 min

1. Greedy Interval Scheduling: One Rule with an Exchange Proof and Three Without

Given NN telescope observation or spectrometer requests [si,fi][s_i, f_i], we seek a maximum-cardinality subset of mutually non-overlapping intervals. Consider four natural greedy rules:

  1. Earliest Start Time (min⁡si\min s_i): Hijacked by one marathon request [0,100][0, 100] blocking dozens of short jobs.

  2. Shortest Duration (min⁡(fi−si)\min (f_i - s_i)): Fooled by one short bridge [4,6][4, 6] straddling [0,5][0, 5] and [5,10][5, 10].

  3. Fewest Conflicts (min⁡deg⁡(i)\min \deg(i)): Even this clever rule fails on a symmetric 11-interval bottleneck graph.

  4. Earliest Finish Time (min⁡fi\min f_i, interval_scheduling_greedy): Always globally optimal.

Stay-Ahead & Exchange Proof: Let greedy select g1,g2,…,gkg_1, g_2, \dots, g_k sorted by finish time, and let any compatible schedule be o1,o2,…,omo_1, o_2, \dots, o_m sorted by finish time.

  • Base case (r=1r=1): Greedy picks minimum finish time overall, so f(g1)≤f(o1)f(g_1) \leq f(o_1).

  • Inductive step: Since f(gr−1)≤f(or−1)≤s(or)f(g_{r-1}) \leq f(o_{r-1}) \leq s(o_r), interval oro_r is compatible with gr−1g_{r-1} and available when greedy chooses grg_r; because greedy minimizes finish time among compatible candidates, f(gr)≤f(or)f(g_r) \leq f(o_r) for every rr. If m>km > k, then s(ok+1)≥f(ok)≥f(gk)s(o_{k+1}) \geq f(o_k) \geq f(g_k), so greedy would have selected at least one more interval—contradiction. Hence k=m∗k = m^*.


Demonstration 1: Earliest finish time against three other greedy rules
======================================================================
Mental Move #17 (Prove Greedy via an Exchange Argument (or Break It)): Evicting furthest-in-future never worsens misses
Earliest start (5 jobs)          : EFT Optimal = 4 jobs vs. earliest_start     = 1 jobs
Shortest duration (3 jobs)       : EFT Optimal = 2 jobs vs. shortest_duration  = 1 jobs
Fewest conflicts (11 jobs)       : EFT Optimal = 4 jobs vs. fewest_conflicts   = 3 jobs
<Figure size 1034x418 with 2 Axes>

Figure 8.1. Interval scheduling on the 11-interval trap. (a) Earliest finish time selects four compatible jobs (green). (b) Fewest conflicts first takes (4.5,6.5)(4.5, 6.5), which has only two conflicts, and ends with three jobs (red).

What Demonstration 1 shows. A greedy rule needs an exchange proof or a counterexample. On ivs_fc11, (4.5, 6.5) conflicts with only 2 intervals while every optimal interval (0,2), (3,5), (6,8), (9,11) conflicts with 3 or 4—yet picking (4.5, 6.5) splits the schedule in the middle and leaves room for 3 jobs instead of EFT’s 4.


2. Offline Optimal Caching: Bélády’s Furthest-in-Future Bound vs. LRU & FIFO

When a CPU cache, GPU tensor buffer, or database page pool of capacity kk suffers a cache miss on request rtr_t, which resident item should it evict?

  • FIFO (First-In, First-Out): Evict the oldest arrival (ignores whether that item is heavily reused).

  • LRU (Least Recently Used): Evict the item whose past access was furthest back—using past recency as an online proxy for future demand.

  • Bélády’s MIN (Furthest-in-Future, 1966): Evict the cached item whose next future appearance in rt+1,…,rTr_{t+1}, \dots, r_T is furthest away (or never occurs again). An exchange argument shows that, for a known request sequence, this policy gives the fewest misses of any policy (Mattson et al. 1970), so greedy_heuristic_search.belady_optimal_cache is the benchmark against which online policies are measured.


Demonstration 2: Bélády furthest-in-future lower bound against LRU and FIFO on Zipfian workload
===============================================================================================
600-request Zipfian phase-shifting trace at cache_size k = 8:
  Belady MIN (Offline Optimal) : 143 misses (hit rate = 76.2%)
  Online LRU                   : 232 misses (hit rate = 61.3%)
  Online FIFO                  : 263 misses (hit rate = 56.2%)
<Figure size 814x451 with 1 Axes>

Figure 8.2. Cache misses on a 600-request synthetic Zipf trace against the cache capacity. Bélády’s furthest-in-future policy is the lower bound; LRU and FIFO lie above it at every capacity.

  • On this phase-shifting Zipf trace, LRU has 232 misses and FIFO 263, against Bélády’s 143. The Bélády count separates two causes of a high miss rate: a poor eviction policy (a large gap MLRU−MBeˊlaˊdyM_{\mathrm{LRU}} - M_{\mathrm{B\acute{e}l\acute{a}dy}}, here 89 misses) and a cache that is too small (a high MBeˊlaˊdyM_{\mathrm{B\acute{e}l\acute{a}dy}} itself).


3. Bélády’s (1969) FIFO Anomaly vs. Mattson’s Stack Inclusion Property

Common sense says giving a program more cache memory (k+1k + 1 slots instead of kk) can never increase its cache misses. Bélády, Nelson and Shedler (1969) showed that this fails for FIFO, with a 12-request trace:

ranomaly=[1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]  ⟹  MFIFO(k=3)=9  <  MFIFO(k=4)=10(3.1)\mathbf{r}_{\mathrm{anomaly}} = [1,\, 2,\, 3,\, 4,\, 1,\, 2,\, 5,\, 1,\, 2,\, 3,\, 4,\, 5] \quad \implies \quad M_{\mathrm{FIFO}}(k=3) = 9 \;<\; M_{\mathrm{FIFO}}(k=4) = 10 \tag{3.1}

Why is LRU immune to Bélády’s Anomaly on every conceivable reference string? Because at every instant tt, LRU’s cache of size kk consists of the kk most recently referenced distinct pages, which is an exact subset of the k+1k + 1 most recently referenced distinct pages (Stack Inclusion Property, Mattson et al., 1970):

CkLRU(t)  ⊆  Ck+1LRU(t)∀t  ⟹  Every hit in k is guaranteed to be a hit in k+1(3.2)\mathcal{C}_k^{\mathrm{LRU}}(t) \;\subseteq\; \mathcal{C}_{k+1}^{\mathrm{LRU}}(t) \quad \forall t \quad \implies \quad \text{Every hit in } k \text{ is guaranteed to be a hit in } k + 1 \tag{3.2}

Demonstration 3: Reproducing Bélády's (1969) FIFO anomaly and verifying LRU stack inclusion
===========================================================================================
Reference string (len=12): [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
  FIFO misses for k = 1..5   : [12, 12, 9, 10, 5]  <-- anomaly: k=3 has 9 misses, k=4 jumps to 10 misses
  LRU misses for k = 1..5    : [12, 12, 10, 8, 5]  (monotone via Stack Inclusion C_3(t) <= C_4(t) at 12/12 steps)
  Belady misses for k = 1..5 : [12, 9, 7, 6, 5]  (monotone optimal lower bound)
  FIFO violates C_3(t) <= C_4(t) at steps t = [6, 7, 10] (e.g. t=6: FIFO_3=[1, 2, 5] not in FIFO_4=[2, 3, 4, 5])
<Figure size 770x440 with 1 Axes>

Figure 8.3. Bélády’s anomaly on the 12-request string. FIFO has 9 misses with 3 frames and 10 with 4; LRU and Bélády’s policy never have more misses with more frames.

Why FIFO Violated Inclusion at Step t=6t = 6 (r = 5): Look at FIFO_3 vs. FIFO_4 right after 5 arrives: in k = 3, pages 1 and 2 had been evicted earlier and re-inserted fresh at steps 4–5 (FIFO_3 = {1, 2, 5}), whereas in k = 4, page 1 never left at step 3 so it remained the oldest arrival and got evicted at step 6 (FIFO_4 = {2, 3, 4, 5}—missing 1, which arrives immediately at step 7).


4. When Greedy Breaks: Canonical vs. Non-Canonical Coin Systems

Making change for integer target AA using US coins {1,5,10,25}\{1, 5, 10, 25\} by repeatedly grabbing the largest coin ≤A\leq A is optimal for every A≥1A \geq 1 (canonical coin system). For an invented system {1,15,25}\{1, 15, 25\} the greedy rule fails for many amounts: 30=25+5×130 = 25 + 5 \times 1 takes 6 greedy coins, against 15+1515 + 15, 2 coins.


Demonstration 4: Canonical [1, 5, 10, 25] against non-canonical [1, 15, 25] greedy change-making
================================================================================================
US [1, 5, 10, 25] greedy failures in 1..80   : 0 (provably canonical)
Invented [1, 15, 25] greedy failures in 1..80 : 31 targets (e.g. A=30: greedy=6 vs. DP=2 coins)
<Figure size 825x440 with 1 Axes>

Figure 8.4. Extra coins used by the greedy rule over the optimum for amounts 1 to 80. The US system {1,5,10,25}\{1, 5, 10, 25\} needs none; the invented system {1,15,25}\{1, 15, 25\} fails for 31 amounts, by up to 8 coins.

Inside the algorithm

Before spending hours trying to write an exchange proof for a brand-new greedy idea, search for a counterexample by computer: compare the candidate greedy rule with an exact solution on all small instances. If a counterexample with three coins or three intervals exists, an exhaustive search finds the smallest one in a fraction of a second. We inspect interval_scheduling_greedy and belady_optimal_cache, then run automated_greedy_counterexample_search().

Check against the library


Inside the algorithm: Greedy interval and Bélády cache + automated counterexample hunter
========================================================================================
def interval_scheduling_greedy(intervals: list[tuple[float, float]]) -> dict:
    """Select a maximum-cardinality mutually compatible set of [start, finish] intervals via earliest finish time."""
    indexed = []
    for idx, (s, f) in enumerate(intervals):
        if f < s:
            raise ValueError(f"Interval {idx} has finish {f} < start {s}.")
        indexed.append((float(f), float(s), idx))
    indexed.sort()

    chosen_idx: list[int] = []
    chosen_iv: list[tuple[float, float]] = []
    last_finish = -math.inf
    for f, s, orig_i in indexed:
        if s >= last_finish - 1e-12:
            chosen_idx.append(orig_i)
            chosen_iv.append((s, f))
            last_finish = f

    return {"selected_intervals": chosen_iv, "selected_indices": chosen_idx, "count": len(chosen_idx)}

def belady_optimal_cache(requests: list[int], cache_size: int) -> dict:
    """Compare Belady's Furthest-in-Future offline optimal cache policy against online LRU and FIFO."""
    k = int(cache_size)
    if k < 1:
        raise ValueError("cache_size must be >= 1.")
    n = len(requests)
    if n == 0:
        return {"belady_misses": 0, "lru_misses": 0, "fifo_misses": 0, "belady_hit_rate": 1.0}

    # 1. Belady's Furthest-in-Future (MIN):
    belady_set: set[int] = set()
    belady_misses = 0
    for i, req in enumerate(requests):
        if req in belady_set:
            continue
        belady_misses += 1
        if len(belady_set) < k:
            belady_set.add(req)
        else:
            # Evict cached item whose next occurrence in requests[i+1:] is furthest (or never appears again):
            victim = None
            furthest_pos = -1
            for item in belady_set:
                try:
                    nxt = requests.index(item, i + 1)
                except ValueError:
                    victim = item
                    break
                if nxt > furthest_pos:
                    furthest_pos = nxt
                    victim = item
            belady_set.remove(victim)  # type: ignore[arg-type]
            belady_set.add(req)

    # 2. Online LRU (Least Recently Used):
    lru_list: list[int] = []
    lru_misses = 0
    for req in requests:
        if req in lru_list:
            lru_list.remove(req)
            lru_list.append(req)
        else:
            lru_misses += 1
            if len(lru_list) == k:
                lru_list.pop(0)
            lru_list.append(req)

    # 3. Online FIFO:
    fifo_q: deque[int] = deque()
    fifo_misses = 0
    for req in requests:
        if req in fifo_q:
            continue
        fifo_misses += 1
        if len(fifo_q) == k:
            fifo_q.popleft()
        fifo_q.append(req)

    return {
        "belady_misses": belady_misses,
        "lru_misses": lru_misses,
        "fifo_misses": fifo_misses,
        "belady_hit_rate": 1.0 - belady_misses / n,
    }

Minimal 3-coin counterexample     : {'coins': [1, 3, 4], 'amount': 6, 'greedy': 3, 'opt': 2} (4+1+1=3 vs. 3+3=2)
Minimal 3-interval counterexample : {'intervals': [(0, 3), (2, 4), (3, 5)], 'shortest_count': 1, 'opt_count': 2}

Exercises

Worked solutions are in 08_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Across 200 random 14-interval schedules, verify that (a) interval_scheduling_greedy matches an exact DP oracle on 100% of trials, and (b) against every compatible schedule (o1,…,om)(o_1, \dots, o_m) sorted by finish time, greedy’s sorted selections (g1,…,gk)(g_1, \dots, g_k) obey f(gr)≤f(or)f(g_r) \leq f(o_r) for all 1≤r≤m1 \leq r \leq m.

  2. Find how it fails. Verify ValueError guards on interval_scheduling_greedy and belady_optimal_cache, audit greedy coin-change suboptimality on [1, 3, 4] (A=6A = 6) and [1, 7, 10] (A=14A = 14), and prove numerically why cyclic scan [0, 1, 2, 3] * 15 in a cache_size = 3 buffer causes 100% misses (60/60) under LRU/FIFO vs. 22 misses under Bélády.

  3. Implement it yourself. Implement weighted_interval_scheduling_dp(intervals_with_weights) in O(Nlog⁡N)\mathcal{O}(N \log N) time using finish-time sorting, binary search (bisect_right) for predecessor p(j)p(j), and Bellman DP with backpointer subset reconstruction. Verify exact optimality against 2N2^N brute-force enumeration across 40 random weighted instances (N = 12) and verify that greedy EFT fails when weights vary.


Self-check for the exercises
============================
All checks passed.