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¶
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.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.Reproduce Bélády’s (1969) FIFO Anomaly () and prove why LRU’s Stack Inclusion Property () guarantees monotone miss rates.
Automate counterexample discovery for non-canonical greedy coin change and implement weighted interval scheduling DP where unit-weight greedy breaks down.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Greedy Interval Scheduling: One Rule with an Exchange Proof and Three Without¶
Given telescope observation or spectrometer requests , we seek a maximum-cardinality subset of mutually non-overlapping intervals. Consider four natural greedy rules:
Earliest Start Time (): Hijacked by one marathon request blocking dozens of short jobs.
Shortest Duration (): Fooled by one short bridge straddling and .
Fewest Conflicts (): Even this clever rule fails on a symmetric 11-interval bottleneck graph.
Earliest Finish Time (,
interval_scheduling_greedy): Always globally optimal.
Stay-Ahead & Exchange Proof: Let greedy select sorted by finish time, and let any compatible schedule be sorted by finish time.
Base case (): Greedy picks minimum finish time overall, so .
Inductive step: Since , interval is compatible with and available when greedy chooses ; because greedy minimizes finish time among compatible candidates, for every . If , then , so greedy would have selected at least one more interval—contradiction. Hence .
heading("Demonstration 1: Earliest finish time against three other greedy rules")
mm17 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 17][0]
print(f"Mental Move #{mm17['id']} ({mm17['name']}): {mm17['invariant']}")
def greedy_by_key(intervals: list[tuple[float, float]], mode: str) -> list[tuple[float, float]]:
rem = list(intervals)
chosen = []
while rem:
if mode == "earliest_start":
best = min(rem, key=lambda iv: (iv[0], iv[1]))
elif mode == "shortest_duration":
best = min(rem, key=lambda iv: (iv[1] - iv[0], iv[0]))
elif mode == "fewest_conflicts":
def deg(cand):
return sum(1 for other in rem if not (other[1] <= cand[0] + 1e-12 or other[0] >= cand[1] - 1e-12))
best = min(rem, key=lambda iv: (deg(iv), iv[0]))
else:
raise ValueError(mode)
chosen.append(best)
rem = [iv for iv in rem if iv[1] <= best[0] + 1e-12 or iv[0] >= best[1] - 1e-12]
return sorted(chosen)
# Counterexample 1 (Earliest Start): [0, 10] blocks [1, 3], [3, 5], [5, 7], [7, 9]
ivs_est = [(0.0, 10.0), (1.0, 3.0), (3.0, 5.0), (5.0, 7.0), (7.0, 9.0)]
# Counterexample 2 (Shortest Duration): [4, 6] blocks [0, 5] and [5, 10]
ivs_short = [(0.0, 5.0), (4.0, 6.0), (5.0, 10.0)]
# Counterexample 3 (Fewest Conflicts — Classic 11-interval graph):
# Top optimal row of 4 disjoint jobs: (0,2), (3,5), (6,8), (9,11)
# Middle trap (4.5, 6.5) has unique minimum conflict degree = 2, whereas 3 left & 3 right blockers give all others degree >= 3
ivs_fc11 = [
(0.0, 2.0), (3.0, 5.0), (6.0, 8.0), (9.0, 11.0),
(4.5, 6.5),
(1.5, 3.5), (1.6, 3.6), (1.7, 3.7),
(7.5, 9.5), (7.6, 9.6), (7.7, 9.7),
]
for label, ivs, bad_mode, expected_opt, expected_bad in [
("Earliest start (5 jobs)", ivs_est, "earliest_start", 4, 1),
("Shortest duration (3 jobs)", ivs_short, "shortest_duration", 2, 1),
("Fewest conflicts (11 jobs)", ivs_fc11, "fewest_conflicts", 4, 3),
]:
opt_eft = greedy_heuristic_search.interval_scheduling_greedy(ivs)
bad_sel = greedy_by_key(ivs, bad_mode)
assert opt_eft["count"] == expected_opt
assert len(bad_sel) == expected_bad
print(f"{label:33s}: EFT Optimal = {opt_eft['count']} jobs vs. {bad_mode:18s} = {len(bad_sel)} jobs")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.4, 3.8), sharex=True)
eft_11 = set(greedy_heuristic_search.interval_scheduling_greedy(ivs_fc11)["selected_intervals"])
fc_11 = set(greedy_by_key(ivs_fc11, "fewest_conflicts"))
for y_i, (s, f) in enumerate(ivs_fc11):
c1 = "#2E8B57" if (s, f) in eft_11 else "#C5CCD3"
c2 = "#C0392B" if (s, f) in fc_11 else "#C5CCD3"
ax1.plot([s, f], [y_i, y_i], lw=5.0, solid_capstyle="butt", color=c1)
ax2.plot([s, f], [y_i, y_i], lw=5.0, solid_capstyle="butt", color=c2)
ax1.set_title("Earliest finish time: 4 disjoint jobs (optimal)")
ax1.set_xlabel("Time $t$")
ax1.set_ylabel("Request index")
ax2.set_title("Fewest conflicts: takes (4.5, 6.5), 3 jobs")
ax2.set_xlabel("Time $t$")
label_panels(fig)
plt.show()
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 8.1. Interval scheduling on the 11-interval trap. (a) Earliest finish time selects four compatible jobs (green). (b) Fewest conflicts first takes , 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 suffers a cache miss on request , 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 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_cacheis the benchmark against which online policies are measured.
heading("Demonstration 2: Bélády furthest-in-future lower bound against LRU and FIFO on Zipfian workload")
rng_z = np.random.default_rng(42)
n_pages = 32
ranks = np.arange(1, n_pages + 1, dtype=float)
zipf_probs = (1.0 / ranks ** 1.12)
zipf_probs /= np.sum(zipf_probs)
# 600-access Zipfian trace with localized bursty hot-set phases:
trace_zipf: list[int] = []
for phase in range(4):
shifted_p = np.roll(zipf_probs, 4 * phase)
trace_zipf.extend(int(x) for x in rng_z.choice(n_pages, size=150, p=shifted_p))
k_sizes = np.arange(1, 17)
m_bel = np.zeros_like(k_sizes)
m_lru = np.zeros_like(k_sizes)
m_fif = np.zeros_like(k_sizes)
for idx, k_val in enumerate(k_sizes):
res_c = greedy_heuristic_search.belady_optimal_cache(trace_zipf, cache_size=int(k_val))
m_bel[idx] = res_c["belady_misses"]
m_lru[idx] = res_c["lru_misses"]
m_fif[idx] = res_c["fifo_misses"]
# Verify Belady optimality bound M_Belady(k) <= min(M_LRU(k), M_FIFO(k)) for EVERY k:
assert np.all(m_bel <= m_lru)
assert np.all(m_bel <= m_fif)
assert int(m_bel[7]) < int(m_lru[7]) <= int(m_fif[7])
print("600-request Zipfian phase-shifting trace at cache_size k = 8:")
print(f" Belady MIN (Offline Optimal) : {m_bel[7]:3d} misses (hit rate = {100.0 * (1.0 - m_bel[7]/600):.1f}%)")
print(f" Online LRU : {m_lru[7]:3d} misses (hit rate = {100.0 * (1.0 - m_lru[7]/600):.1f}%)")
print(f" Online FIFO : {m_fif[7]:3d} misses (hit rate = {100.0 * (1.0 - m_fif[7]/600):.1f}%)")
fig, ax = plt.subplots(figsize=(7.4, 4.1))
ax.plot(k_sizes, m_fif, marker="^", lw=1.9, ls="--", color="#C0392B", label="Online FIFO misses")
ax.plot(k_sizes, m_lru, marker="s", lw=2.1, color="#E08214", label="Online LRU misses")
ax.plot(k_sizes, m_bel, marker="o", lw=2.4, color="#2166AC", label="Bélády furthest-in-future (global optimum)")
ax.set_xlabel("Cache capacity $k$ [pages]")
ax.set_ylabel("Total cache misses (out of 600)")
ax.set_title("Bélády's optimum against LRU and FIFO")
ax.legend(fontsize=8.5)
plt.show()
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 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 , here 89 misses) and a cache that is too small (a high itself).
3. Bélády’s (1969) FIFO Anomaly vs. Mattson’s Stack Inclusion Property¶
Common sense says giving a program more cache memory ( slots instead of ) can never increase its cache misses. Bélády, Nelson and Shedler (1969) showed that this fails for FIFO, with a 12-request trace:
Why is LRU immune to Bélády’s Anomaly on every conceivable reference string? Because at every instant , LRU’s cache of size consists of the most recently referenced distinct pages, which is an exact subset of the most recently referenced distinct pages (Stack Inclusion Property, Mattson et al., 1970):
heading("Demonstration 3: Reproducing Bélády's (1969) FIFO anomaly and verifying LRU stack inclusion")
trace_belady_1969 = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
ks_anom = np.arange(1, 6)
f_m = [greedy_heuristic_search.belady_optimal_cache(trace_belady_1969, int(k))["fifo_misses"] for k in ks_anom]
l_m = [greedy_heuristic_search.belady_optimal_cache(trace_belady_1969, int(k))["lru_misses"] for k in ks_anom]
b_m = [greedy_heuristic_search.belady_optimal_cache(trace_belady_1969, int(k))["belady_misses"] for k in ks_anom]
# 1. Exact reproduction of Belady, Nelson & Shedler (1969): FIFO(k=3) = 9 < FIFO(k=4) = 10
assert f_m[2] == 9 and f_m[3] == 10 and f_m[3] > f_m[2]
# 2. Both LRU and Belady MIN are monotonically non-increasing:
assert np.all(np.diff(l_m) <= 0) and np.all(np.diff(b_m) <= 0)
# 3. Direct step-by-step verification of Stack Inclusion C_3(t) <= C_4(t) for LRU vs. violation for FIFO:
def trace_caches_step_by_step(requests: list[int], k: int) -> tuple[list[set[int]], list[set[int]]]:
lru: list[int] = []
fifo: list[int] = []
lru_snaps, fifo_snaps = [], []
for r in requests:
if r in lru:
lru.remove(r)
lru.append(r)
else:
if len(lru) == k:
lru.pop(0)
lru.append(r)
if r not in fifo:
if len(fifo) == k:
fifo.pop(0)
fifo.append(r)
lru_snaps.append(set(lru))
fifo_snaps.append(set(fifo))
return lru_snaps, fifo_snaps
lru_3, fifo_3 = trace_caches_step_by_step(trace_belady_1969, 3)
lru_4, fifo_4 = trace_caches_step_by_step(trace_belady_1969, 4)
assert all(s3.issubset(s4) for s3, s4 in zip(lru_3, lru_4))
fifo_subset_violations = [t for t, (s3, s4) in enumerate(zip(fifo_3, fifo_4)) if not s3.issubset(s4)]
assert len(fifo_subset_violations) > 0
print(f"Reference string (len=12): {trace_belady_1969}")
print(f" FIFO misses for k = 1..5 : {f_m} <-- anomaly: k=3 has 9 misses, k=4 jumps to 10 misses")
print(f" LRU misses for k = 1..5 : {l_m} (monotone via Stack Inclusion C_3(t) <= C_4(t) at 12/12 steps)")
print(f" Belady misses for k = 1..5 : {b_m} (monotone optimal lower bound)")
print(f" FIFO violates C_3(t) <= C_4(t) at steps t = {fifo_subset_violations} (e.g. t={fifo_subset_violations[0]}: FIFO_3={sorted(fifo_3[fifo_subset_violations[0]])} not in FIFO_4={sorted(fifo_4[fifo_subset_violations[0]])})")
fig, ax = plt.subplots(figsize=(7.0, 4.0))
ax.plot(ks_anom, f_m, marker="^", ms=7, lw=2.3, color="#C0392B", label="FIFO (anomaly at $k=3 \\rightarrow 4$)")
ax.plot(ks_anom, l_m, marker="s", ms=6, lw=2.1, color="#E08214", label="LRU (stack inclusion monotone)")
ax.plot(ks_anom, b_m, marker="o", ms=6, lw=2.2, color="#2166AC", label="Bélády furthest-in-future")
ax.annotate("More frames, more misses", xy=(4, 10), xytext=(2.55, 11.1), arrowprops={"arrowstyle": "->", "color": "#C0392B", "lw": 1.6}, color="#C0392B", fontsize=9)
ax.set_xticks(ks_anom)
ax.set_ylim(4.0, 12.3)
ax.set_xlabel("Cache capacity $k$ [frames]")
ax.set_ylabel("Page faults / misses")
ax.set_title("The FIFO anomaly of Bélády, Nelson and Shedler (1969)")
ax.legend(fontsize=8.5)
plt.show()
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 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 (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 using US coins by repeatedly grabbing the largest coin is optimal for every (canonical coin system). For an invented system the greedy rule fails for many amounts: takes 6 greedy coins, against , 2 coins.
heading("Demonstration 4: Canonical [1, 5, 10, 25] against non-canonical [1, 15, 25] greedy change-making")
def coin_change_dp_and_greedy(coins: list[int], max_amount: int) -> tuple[np.ndarray, np.ndarray]:
c_sorted = sorted(coins, reverse=True)
dp = np.full(max_amount + 1, 10**9, dtype=int)
dp[0] = 0
for a in range(1, max_amount + 1):
dp[a] = min(dp[a - c] + 1 for c in c_sorted if c <= a)
grd = np.zeros(max_amount + 1, dtype=int)
for a in range(1, max_amount + 1):
rem = a
cnt = 0
for c in c_sorted:
q, rem = divmod(rem, c)
cnt += q
grd[a] = cnt
return dp, grd
dp_us, grd_us = coin_change_dp_and_greedy([1, 5, 10, 25], 80)
dp_nc, grd_nc = coin_change_dp_and_greedy([1, 15, 25], 80)
assert np.array_equal(dp_us, grd_us) # [1, 5, 10, 25] is 100% canonical
assert grd_nc[30] == 6 and dp_nc[30] == 2 # 25+1+1+1+1+1 (6) vs. 15+15 (2): 3x too many coins
fail_amounts = np.flatnonzero(grd_nc > dp_nc)
print(f"US [1, 5, 10, 25] greedy failures in 1..80 : {int(np.sum(grd_us != dp_us))} (provably canonical)")
print(f"Invented [1, 15, 25] greedy failures in 1..80 : {len(fail_amounts)} targets (e.g. A=30: greedy={grd_nc[30]} vs. DP={dp_nc[30]} coins)")
amounts = np.arange(1, 81)
fig, ax = plt.subplots(figsize=(7.5, 4.0))
ax.plot(amounts, grd_nc[1:] - dp_nc[1:], lw=2.0, color="#C0392B", label="Non-canonical [1, 15, 25] excess coins ($C_{\\mathrm{greedy}} - C^*$)")
ax.plot(amounts, grd_us[1:] - dp_us[1:], lw=2.2, ls="--", color="#2166AC", label="Canonical [1, 5, 10, 25] excess coins ($0$ everywhere)")
ax.set_xlabel("Target amount $A$")
ax.set_ylabel("Greedy suboptimality gap [extra coins]")
ax.set_title("One changed coin breaks the greedy rule")
ax.legend(fontsize=8.5)
plt.show()
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 8.4. Extra coins used by the greedy rule over the optimum for amounts 1 to 80. The US system needs none; the invented system 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¶
heading("Inside the algorithm: Greedy interval and Bélády cache + automated counterexample hunter")
print(show_source(greedy_heuristic_search.interval_scheduling_greedy))
print(show_source(greedy_heuristic_search.belady_optimal_cache))
def automated_greedy_counterexample_search() -> dict:
"""Discover minimal 3-coin and 3-interval counterexamples breaking plausible greedy heuristics."""
# 1. Lexicographically smallest 3-coin system (1 < c2 < c3) where greedy fails, plus minimal target A:
min_coin_ce = None
for c3 in range(3, 12):
for c2 in range(2, c3):
dp_c, gr_c = coin_change_dp_and_greedy([1, c2, c3], 2 * c3)
bad = np.flatnonzero(gr_c > dp_c)
if bad.size > 0:
a_min = int(bad[0])
min_coin_ce = {"coins": [1, c2, c3], "amount": a_min, "greedy": int(gr_c[a_min]), "opt": int(dp_c[a_min])}
break
if min_coin_ce is not None:
break
# 2. Minimal integer 3-interval counterexample on [0..6] breaking Shortest-Duration greedy:
min_iv_ce = None
coords = [(s, f) for s in range(7) for f in range(s + 1, 7)]
for i in range(len(coords)):
for j in range(i + 1, len(coords)):
for k in range(j + 1, len(coords)):
tri = [coords[i], coords[j], coords[k]]
c_opt = greedy_heuristic_search.interval_scheduling_greedy(tri)["count"]
c_short = len(greedy_by_key(tri, "shortest_duration"))
if c_short < c_opt:
min_iv_ce = {"intervals": tri, "shortest_count": c_short, "opt_count": c_opt}
break
if min_iv_ce is not None:
break
if min_iv_ce is not None:
break
return {"coin_counterexample": min_coin_ce, "interval_counterexample": min_iv_ce}
ce_found = automated_greedy_counterexample_search()
assert ce_found["coin_counterexample"]["coins"] == [1, 3, 4]
assert ce_found["coin_counterexample"]["amount"] == 6
assert ce_found["interval_counterexample"]["opt_count"] == 2 and ce_found["interval_counterexample"]["shortest_count"] == 1
print(f"Minimal 3-coin counterexample : {ce_found['coin_counterexample']} (4+1+1=3 vs. 3+3=2)")
print(f"Minimal 3-interval counterexample : {ce_found['interval_counterexample']}")
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.
Verify a result. Across 200 random 14-interval schedules, verify that (a)
interval_scheduling_greedymatches an exact DP oracle on 100% of trials, and (b) against every compatible schedule sorted by finish time, greedy’s sorted selections obey for all .Find how it fails. Verify
ValueErrorguards oninterval_scheduling_greedyandbelady_optimal_cache, audit greedy coin-change suboptimality on[1, 3, 4]() and[1, 7, 10](), and prove numerically why cyclic scan[0, 1, 2, 3] * 15in acache_size = 3buffer causes 100% misses (60/60) under LRU/FIFO vs.22misses under Bélády.Implement it yourself. Implement
weighted_interval_scheduling_dp(intervals_with_weights)in time using finish-time sorting, binary search (bisect_right) for predecessor , and Bellman DP with backpointer subset reconstruction. Verify exact optimality against brute-force enumeration across 40 random weighted instances (N = 12) and verify that greedy EFT fails when weights vary.
heading("Self-check for the exercises")
assert greedy_heuristic_search.interval_scheduling_greedy(ivs_fc11)["count"] == 4
assert np.all(m_bel <= m_lru) and np.all(m_bel <= m_fif)
assert f_m[2] == 9 and f_m[3] == 10 and all(s3.issubset(s4) for s3, s4 in zip(lru_3, lru_4))
assert ce_found["coin_counterexample"]["coins"] == [1, 3, 4] and ce_found["coin_counterexample"]["amount"] == 6
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.