Worked solutions to the three exercises of Lecture 3. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: Doubling-ratio diagnostics across canonical scaling laws")
sizes = np.array([64, 128, 256, 512, 1024, 2048, 4096], dtype=float)
synthetic_work = {
"Constant lookup": np.full_like(sizes, 4.0),
"Binary halving": np.log2(sizes),
"Single linear scan": 2.5 * sizes,
"Divide and conquer": 1.2 * sizes * np.log2(sizes),
"All-pairs quadratic": 0.5 * sizes * (sizes - 1.0),
}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.2))
print(f"{'Pattern':22s} | {'Fitted p':>8s} | {'Last C(2N)/C(N)':>15s} | {'Classified Class':>16s}")
print("-" * 70)
for label, work_arr in synthetic_work.items():
fit = invariants_complexity.fit_empirical_complexity(sizes, work_arr)
last_ratio = float(fit["step_ratios"][-1])
print(f"{label:22s} | {fit['exponent_p']:8.3f} | {last_ratio:15.3f} | {fit['complexity_class']:>16s}")
ax1.loglog(sizes, work_arr, "o-", lw=2.0, label=f"{label} ({fit['complexity_class']})")
ax2.semilogx(sizes[1:], fit["local_exponents"], "s--", lw=1.8, label=label)
ax1.set_xlabel("Problem size $N$")
ax1.set_ylabel("Elementary operations $C(N)$")
ax1.set_title("Cost against size over six doublings")
ax1.legend(fontsize=7.8)
ax2.set_xlabel("Doubled size $2N$")
ax2.set_ylabel(r"Local doubling exponent $\log_2(C(2N)/C(N))$")
ax2.set_title("Local doubling exponent")
ax2.legend(fontsize=7.8, loc="center right", bbox_to_anchor=(1.0, 0.32))
log_ticks(ax2, "x", [128, 256, 512, 1024, 2048, 4096])
label_panels(fig)
plt.show()
assert invariants_complexity.fit_empirical_complexity(sizes, synthetic_work["Constant lookup"])["complexity_class"] == "O(1)"
assert invariants_complexity.fit_empirical_complexity(sizes, synthetic_work["Binary halving"])["complexity_class"] == "O(log N)"
assert invariants_complexity.fit_empirical_complexity(sizes, synthetic_work["Single linear scan"])["complexity_class"] == "O(N)"
assert invariants_complexity.fit_empirical_complexity(sizes, synthetic_work["Divide and conquer"])["complexity_class"] == "O(N log N)"
assert invariants_complexity.fit_empirical_complexity(sizes, synthetic_work["All-pairs quadratic"])["complexity_class"] == "O(N^2)"
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify Tarjan’s exact potential telescoping identity total_pushes - total_pops == final_deque_len >= 1 and total_pushes + total_pops <= 2*N - 1 on invariants_complexity.sliding_window_max_monotonic_deque across strictly increasing, strictly decreasing, sawtooth, and impulse signals ().
heading("Exercise 1: Tarjan potential function verification across adversarial signals")
n_adv, k_adv = 3000, 200
idx_arr = np.arange(n_adv, dtype=float)
adversarial_signals = {
"Strictly increasing ramp": idx_arr,
"Strictly decreasing ramp": -idx_arr,
"High-frequency sawtooth": np.mod(idx_arr, 37.0),
"Sparse impulses": ((np.mod(idx_arr, 199.0) == 0).astype(float)) * 100.0,
}
print(f"{'Signal Waveform':26s} | {'Pushes':>7s} | {'Pops':>7s} | {'Final Phi_N':>11s} | {'Pushes+Pops':>12s} | {'Bound 2N-1':>10s}")
print("-" * 86)
for name, sig in adversarial_signals.items():
res = invariants_complexity.sliding_window_max_monotonic_deque(sig, k_adv)
phi_final = res["total_pushes"] - res["total_pops"]
tot_ops = res["total_pushes"] + res["total_pops"]
print(f"{name:26s} | {res['total_pushes']:7d} | {res['total_pops']:7d} | {phi_final:11d} | {tot_ops:12d} | {2*n_adv - 1:10d}")
assert res["total_pushes"] == n_adv
assert 1 <= phi_final <= k_adv
assert tot_ops == 2 * n_adv - phi_final <= 2 * n_adv - 1
assert res["element_comparisons"] <= 2 * n_adv - 1
# Notice the two extremes: Increasing ramp pops EVERY prior element immediately (Phi_N = 1, Pops = N-1);
# Decreasing ramp NEVER pops from the back, only expiring from the front once i >= k (Phi_N = k, Pops = N-k)!
Exercise 1: Tarjan potential function verification across adversarial signals
=============================================================================
Signal Waveform | Pushes | Pops | Final Phi_N | Pushes+Pops | Bound 2N-1
--------------------------------------------------------------------------------------
Strictly increasing ramp | 3000 | 2999 | 1 | 5999 | 5999
Strictly decreasing ramp | 3000 | 2800 | 200 | 5800 | 5999
High-frequency sawtooth | 3000 | 2998 | 2 | 5998 | 5999
Sparse impulses | 3000 | 2998 | 2 | 5998 | 5999
Explanation. Pushing an element stores +1 unit of potential in the deque, and every future pop pays for itself by releasing -1 unit of stored potential. Because and at loop end, holds as an exact algebraic identity regardless of whether pops happen 1-by-1 (increasing ramp, ) or in sudden bursts of at once (sawtooth).
Exercise 2¶
Problem. Quantify (a) exact element-shift operations in list.pop(0) vs. deque.popleft() across , and (b) silent false-negative neighbor misses when a cell-list search uses an undersized cell width .
heading("Exercise 2: Audit of hidden O(N^2) list.pop(0) and undersized cell width h < r_c")
# (a) Draining an N-element FIFO queue: list.pop(0) shifts (m - 1) C-pointers on every pop
q_sizes = np.array([500, 1000, 2000, 4000], dtype=float)
list_shift_ops = 0.5 * q_sizes * (q_sizes - 1.0)
deque_ops = q_sizes.copy()
fit_list_pop0 = invariants_complexity.fit_empirical_complexity(q_sizes, list_shift_ops)
fit_deque_pop = invariants_complexity.fit_empirical_complexity(q_sizes, deque_ops)
print(f"(a) FIFO drain scaling: list.pop(0) shifts -> {fit_list_pop0['complexity_class']} (p={fit_list_pop0['exponent_p']:.2f}) vs deque.popleft() -> {fit_deque_pop['complexity_class']}")
# (b) Buggy 3x3 cell-list finder that buckets with cell width h_bad < cutoff_r:
def buggy_subcutoff_cell_list(coords: np.ndarray, cutoff_r: float, h_cell: float) -> list[tuple[int, int]]:
pts = np.asarray(coords, dtype=float)
r2 = cutoff_r * cutoff_r
buckets: dict[tuple[int, int], list[int]] = {}
for idx in range(pts.shape[0]):
buckets.setdefault((math.floor(pts[idx, 0] / h_cell), math.floor(pts[idx, 1] / h_cell)), []).append(idx)
found = []
for (cx, cy), mem in buckets.items():
for a in range(len(mem)):
for b in range(a + 1, len(mem)):
i, j = mem[a], mem[b]
if (pts[i, 0] - pts[j, 0]) ** 2 + (pts[i, 1] - pts[j, 1]) ** 2 <= r2:
found.append((min(i, j), max(i, j)))
for dx_c, dy_c in [(0, 1), (1, -1), (1, 0), (1, 1)]:
for i in mem:
for j in buckets.get((cx + dx_c, cy + dy_c), []):
if (pts[i, 0] - pts[j, 0]) ** 2 + (pts[i, 1] - pts[j, 1]) ** 2 <= r2:
found.append((min(i, j), max(i, j)))
found.sort()
return found
rng_bug = np.random.default_rng(88)
pts_test = rng_bug.uniform(0.0, 12.0, size=(300, 2))
rc = 1.50
true_pairs = invariants_complexity.brute_force_neighbors(pts_test, rc)
good_h_pairs = buggy_subcutoff_cell_list(pts_test, rc, h_cell=rc)
bad_h_pairs = buggy_subcutoff_cell_list(pts_test, rc, h_cell=0.50 * rc)
missed_pct = 100.0 * (len(true_pairs) - len(bad_h_pairs)) / len(true_pairs)
print(f"(b) True pairs (r_c={rc}): {len(true_pairs)} | h = 1.0*r_c found: {len(good_h_pairs)} | h = 0.5*r_c found: {len(bad_h_pairs)} (missed {missed_pct:.1f}% of true neighbors)")
assert fit_list_pop0["complexity_class"] == "O(N^2)"
assert good_h_pairs == true_pairs
assert missed_pct > 20.0
Exercise 2: Audit of hidden O(N^2) list.pop(0) and undersized cell width h < r_c
================================================================================
(a) FIFO drain scaling: list.pop(0) shifts -> O(N^2) (p=2.00) vs deque.popleft() -> O(N)
(b) True pairs (r_c=1.5): 1943 | h = 1.0*r_c found: 1943 | h = 0.5*r_c found: 1413 (missed 27.3% of true neighbors)
Explanation. Python’s list is a contiguous array of pointers, so pop(0) calls memmove on all remaining elements (). With cells of width , two points apart can land in cells and , outside the stencil (|dc| <= 1); here 27.3 % of the true pairs are missed, and in a molecular dynamics run the corresponding short-range repulsive forces would be lost without any error message.
Exercise 3¶
Problem. Implement largest_zero_defect_rectangle_histogram(heights) using an increasing monotonic stack in strictly time (pushes == N + 1 including sentinel 0, pops <= N), returning max_area, best_span (left_idx, right_idx_exclusive, height), pushes, and pops. Verify exact equality against an brute-force oracle on 40 random and structured histograms.
heading("Exercise 3: Implement it yourself — O(N) monotonic stack largest histogram rectangle")
def largest_zero_defect_rectangle_histogram(heights: np.ndarray) -> dict:
"""Find largest axis-aligned rectangle under histogram in O(N) via strictly increasing index stack."""
h_arr = np.asarray(heights, dtype=float).ravel()
if h_arr.size == 0 or np.any(h_arr < 0.0):
raise ValueError("heights must be non-empty and non-negative.")
n = h_arr.size
# Append trailing sentinel height -1.0 at index n to flush all remaining open bars cleanly:
stack: list[int] = []
max_area = 0.0
best_rect = (0, 0, 0.0)
pushes = 0
pops = 0
for i in range(n + 1):
cur_h = float(h_arr[i]) if i < n else -1.0
while stack and float(h_arr[stack[-1]]) > cur_h:
top_idx = stack.pop()
pops += 1
bar_h = float(h_arr[top_idx])
left_bound = (stack[-1] + 1) if stack else 0
width = i - left_bound
area = bar_h * width
if area > max_area:
max_area = area
best_rect = (left_bound, i, bar_h)
if i < n:
stack.append(i)
pushes += 1
return {"max_area": max_area, "best_rect": best_rect, "pushes": pushes, "pops": pops}
def _brute_histogram_oracle(heights: np.ndarray) -> float:
h = np.asarray(heights, dtype=float).ravel()
best = 0.0
for i in range(h.size):
min_h = float(h[i])
for j in range(i, h.size):
min_h = min(min_h, float(h[j]))
best = max(best, min_h * (j - i + 1))
return best
classic_bars = np.array([2.0, 1.0, 5.0, 6.0, 2.0, 3.0])
classic_res = largest_zero_defect_rectangle_histogram(classic_bars)
print(f"Classic [2, 1, 5, 6, 2, 3] -> max_area = {classic_res['max_area']:.1f}, rect (l, r, h) = {classic_res['best_rect']}")
assert classic_res["max_area"] == 10.0 and classic_res["best_rect"] == (2, 4, 5.0)
rng_hist = np.random.default_rng(404)
for t_idx in range(40):
n_b = 90
if t_idx == 0:
bars = np.arange(1.0, n_b + 1.0)
elif t_idx == 1:
bars = np.arange(float(n_b), 0.0, -1.0)
elif t_idx == 2:
bars = np.full(n_b, 7.5)
else:
bars = rng_hist.integers(0, 50, size=n_b).astype(float)
st_out = largest_zero_defect_rectangle_histogram(bars)
bf_area = _brute_histogram_oracle(bars)
assert np.isclose(st_out["max_area"], bf_area, rtol=1e-14)
assert st_out["pushes"] == n_b and st_out["pops"] == n_b
print("Verified 100% optimality across 40 structured + random histograms with exact pushes == pops == N")
Exercise 3: Implement it yourself — O(N) monotonic stack largest histogram rectangle
====================================================================================
Classic [2, 1, 5, 6, 2, 3] -> max_area = 10.0, rect (l, r, h) = (2, 4, 5.0)
Verified 100% optimality across 40 structured + random histograms with exact pushes == pops == N
Summary. Whenever a bar at top_idx is popped by a shorter bar at i, i is its first shorter bar on the right, and the new stack top stack[-1] (by the increasing-stack invariant) is its first shorter-or-equal bar on the left. One pass thus discovers the maximal horizontal span of every bar simultaneously.