When a laboratory data pipeline takes 10 minutes to process particles or infrared frames, the first idea is often to rewrite the loops in C++ or to rent a GPU. If the algorithm is , however, going to multiplies the run time by 104, turning 10 minutes into about ten weeks on any hardware. Changing what the data structure remembers from one step to the next can instead give speed-ups of a thousand or more in plain Python. This lecture covers Mental Moves #7–#10 via invariants_complexity: doubling-ratio diagnostics (fit_empirical_complexity), 2-D summed-area prefix tables (prefix_sum_2d_integral), amortized monotonic deques (sliding_window_max_monotonic_deque), and spatial cell-list hashing (spatial_cell_list_neighbors).
Learning objectives¶
Diagnose empirical time/operation complexity via log-log slopes and doubling ratios using
invariants_complexity.fit_empirical_complexity.Evaluate arbitrary 2-D rectangular flux integrals in strictly 4 array lookups ( per query) via inclusion–exclusion in
invariants_complexity.prefix_sum_2d_integral.Compute all sliding-window maxima of width in strictly amortized deque operations (independent of ) using
invariants_complexity.sliding_window_max_monotonic_deque.Accelerate 2-D short-range particle neighbor discovery from to expected time via
invariants_complexity.spatial_cell_list_neighbors, verified againstbrute_force_neighbors.
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. Empirical Doubling Ratios Before Micro-Tuning (fit_empirical_complexity)¶
Mental Move #7, Measure Doubling Ratios Before Micro-Tuning: Before touching a profiler or compiler flag, evaluate operation count or wall time across geometric doublings . If , doubling multiplies cost by a constant ratio:
A ratio near 1.0 signals or ; 2.0 signals (or for ); 4.0 signals ; and 8.0 signals .
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)"
Demonstration 1: Doubling-ratio diagnostics across canonical scaling laws
=========================================================================
Pattern | Fitted p | Last C(2N)/C(N) | Classified Class
----------------------------------------------------------------------
Constant lookup | -0.000 | 1.000 | O(1)
Binary halving | 0.165 | 1.091 | O(log N)
Single linear scan | 1.000 | 2.000 | O(N)
Divide and conquer | 1.165 | 2.182 | O(N log N)
All-pairs quadratic | 2.003 | 4.001 | O(N^2)

Figure 3.1. Doubling-ratio diagnostics for five synthetic cost laws. (a) Operation counts on log-log axes. (b) The local exponent : it settles at 0, 1 and 2 for constant, linear and quadratic cost, decreases slowly towards 0 for , and stays a little above 1 for .
What Demonstration 1 shows.
At ,
All-pairs quadraticalready executes operations vs. forSingle linear scan( slower), and every subsequent increase in sensor resolution widens that gap by another factor of 10.
2. Summed-Area Prefix Integrals for Rectangular Queries (prefix_sum_2d_integral)¶
Suppose an infrared thermography camera captures an heat-flux map across a battery module, and a thermal controller evaluates candidate cooling-zone rectangles . Summing each subarray naively takes additions. Mental Move #8, Precompute Prefix Integrals for Queries (Crow 1984; Viola–Jones 2001) builds the cumulative table once in and answers any rectangle of any size in exactly 4 table lookups via inclusion–exclusion:
heading("Demonstration 2: 1,000 rectangular thermal-flux queries in 4,000 lookups via 2-D prefix integrals")
rng_sat = np.random.default_rng(303)
h_grid, w_grid = 120, 120
yy, xx = np.mgrid[0:h_grid, 0:w_grid]
heat_flux = (
450.0
+ 1800.0 * np.exp(-((xx - 38.0) ** 2 + (yy - 44.0) ** 2) / 220.0)
+ 1450.0 * np.exp(-((xx - 86.0) ** 2 + (yy - 78.0) ** 2) / 180.0)
+ rng_sat.uniform(0.0, 35.0, size=(h_grid, w_grid))
)
n_queries = 1000
queries = []
naive_cell_adds = 0
oracle_sums = np.empty(n_queries, dtype=float)
for q_i in range(n_queries):
r0, r1 = sorted(rng_sat.integers(0, h_grid, size=2).tolist())
c0, c1 = sorted(rng_sat.integers(0, w_grid, size=2).tolist())
queries.append((r0, c0, r1, c1))
naive_cell_adds += (r1 - r0 + 1) * (c1 - c0 + 1)
oracle_sums[q_i] = float(np.sum(heat_flux[r0 : r1 + 1, c0 : c1 + 1]))
sat_res = invariants_complexity.prefix_sum_2d_integral(heat_flux, queries)
max_abs_err = float(np.max(np.abs(sat_res["sums"] - oracle_sums)))
total_sat_ops = h_grid * w_grid + sat_res["table_lookups"]
print(f"Grid = {h_grid}x{w_grid} ({h_grid*w_grid:,d} cells) | Queries = {n_queries:,d}")
print(f"Naive subarray cell additions : {naive_cell_adds:,d} ops")
print(f"2-D Prefix Table build + 4Q : {h_grid*w_grid:,d} + {sat_res['table_lookups']:,d} = {total_sat_ops:,d} ops ({naive_cell_adds/total_sat_ops:.1f}x reduction)")
print(f"Max |PrefixIntegral - Oracle| : {max_abs_err:.2e} W/m^2")
assert sat_res["table_lookups"] == 4 * n_queries
assert np.allclose(sat_res["sums"], oracle_sums, rtol=1e-12)
Demonstration 2: 1,000 rectangular thermal-flux queries in 4,000 lookups via 2-D prefix integrals
=================================================================================================
Grid = 120x120 (14,400 cells) | Queries = 1,000
Naive subarray cell additions : 1,688,282 ops
2-D Prefix Table build + 4Q : 14,400 + 4,000 = 18,400 ops (91.8x reduction)
Max |PrefixIntegral - Oracle| : 8.38e-09 W/m^2
What Demonstration 2 shows.
Even for just queries on a sensor array, inclusion–exclusion reduces the arithmetic by a factor of 92 (the queries alone fall from cell reads to lookups, a factor of about 420).
3. Amortized Sliding-Window Maxima via Monotonic Deques (sliding_window_max_monotonic_deque)¶
To detect transient overpressure envelopes over a rolling window of width across samples, np.array([np.max(x[i:i+k]) for i in range(N-k+1)]) performs comparisons, taking quadratic work when .
Mental Move #9, Prune Dominated Candidates in a Monotonic Queue: Suppose index is still inside the current window, and the newly arrived sample satisfies . Because is both older (expires sooner) and smaller than , can never be the maximum of this or any future window. Popping all such dominated indices from the back of a double-ended queue maintains a strictly decreasing value invariant arr[dq[0]] > arr[dq[1]] > ..., making the window maximum arr[dq[0]] in . Because each index enters the deque once and leaves at most once, total pushes + pops is bounded by for ANY window width .
heading("Demonstration 3: Monotonic deque envelope detection — <= 2N ops independent of window width k")
rng_dq = np.random.default_rng(55)
n_sig = 6000
t_grid = np.linspace(0.0, 12.0, n_sig)
turb_sig = np.sin(2.2 * t_grid) + 0.6 * np.cos(9.5 * t_grid) + rng_dq.exponential(0.45, size=n_sig)
k_widths = [10, 50, 250, 1000, 2500]
naive_comps_list, deque_comps_list = [], []
print(f"{'Window k':>8s} | {'Naive Comparisons':>18s} | {'Deque Pushes':>12s} | {'Deque Pops':>10s} | {'Deque Comps (<2N)':>18s} | {'Speedup':>9s}")
print("-" * 90)
for k_w in k_widths:
dq_res = invariants_complexity.sliding_window_max_monotonic_deque(turb_sig, k_w)
oracle_max = np.array([np.max(turb_sig[i : i + k_w]) for i in range(n_sig - k_w + 1)])
assert np.array_equal(dq_res["window_maxima"], oracle_max)
naive_c = (n_sig - k_w + 1) * (k_w - 1)
naive_comps_list.append(naive_c)
deque_comps_list.append(dq_res["element_comparisons"])
sp_k = naive_c / max(1, dq_res["element_comparisons"])
print(f"{k_w:8d} | {naive_c:18,d} | {dq_res['total_pushes']:12,d} | {dq_res['total_pops']:10,d} | {dq_res['element_comparisons']:18,d} | {sp_k:8.1f}x")
assert dq_res["total_pushes"] == n_sig
assert dq_res["total_pops"] <= n_sig
assert dq_res["element_comparisons"] < 2 * n_sig
env_400 = invariants_complexity.sliding_window_max_monotonic_deque(turb_sig[:800], 60)["window_maxima"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.1))
ax1.plot(turb_sig[:800], color="#A9C9E8", lw=1.0, label="Raw turbulent sensor signal")
ax1.plot(np.arange(59, 800), env_400, color="#C0392B", lw=2.0, label="Rolling peak envelope ($k = 60$)")
ax1.set_xlabel("Sample index $i$")
ax1.set_ylabel("Pressure fluctuation [kPa]")
ax1.set_title("Rolling maximum from a monotonic deque")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.2)
ax2.loglog(k_widths, naive_comps_list, "o-", color="#C0392B", lw=2.2, label=r"Naive window scan $\mathcal{O}(N k)$")
ax2.loglog(k_widths, deque_comps_list, "s--", color="#2E8B57", lw=2.2, label=r"Monotonic deque $\leq 2N$ (flat in $k$)")
ax2.set_xlabel("Sliding window width $k$ [samples]")
ax2.set_ylabel("Total element comparisons")
ax2.set_title("Comparisons against window width")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Demonstration 3: Monotonic deque envelope detection — <= 2N ops independent of window width k
=============================================================================================
Window k | Naive Comparisons | Deque Pushes | Deque Pops | Deque Comps (<2N) | Speedup
------------------------------------------------------------------------------------------
10 | 53,919 | 6,000 | 5,998 | 10,770 | 5.0x
50 | 291,599 | 6,000 | 5,997 | 11,733 | 24.9x
250 | 1,431,999 | 6,000 | 5,997 | 11,924 | 120.1x
1000 | 4,995,999 | 6,000 | 5,997 | 11,978 | 417.1x
2500 | 8,748,999 | 6,000 | 5,996 | 11,989 | 729.8x

Figure 3.2. Sliding-window maxima. (a) A synthetic turbulent pressure signal and its rolling maximum over a window of 60 samples. (b) Comparisons against the window width : the naive scan grows as , the monotonic deque stays below for every .
At , naive scanning performs comparisons while the monotonic deque performs , a reduction by a factor of 730, with identical output. The deque’s count stays below for every window width.
4. Spatial Cell-List Hashing Reduces All-Pairs into (spatial_cell_list_neighbors)¶
In molecular dynamics (Lennard-Jones cutoff ), smoothed-particle hydrodynamics (SPH), and granular DEM contact detection, only particle pairs within Euclidean distance interact. Testing all pairs spends almost all the work on distant particles: at only 0.25 % of the pairs interact.
Mental Move #10, Bucket Space into Cutoff Cells: Partition 2-D space into uniform square cells of side length via integer floor hashing . Any neighbor within distance of a particle in cell must reside in or one of its 8 adjacent Moore neighbors (and testing just 4 forward half-stencil offsets [(0,1), (1,-1), (1,0), (1,1)] plus intra-cell pairs checks every candidate pair at most once). At constant physical particle density , each cell holds particles, reducing total distance checks to strictly .
heading("Demonstration 4: Spatial cell-list hashing O(N) against brute-force all-pairs O(N^2)")
rng_cl = np.random.default_rng(77)
cutoff_rc = 1.25
density_rho = 0.80 # Constant physical number density [particles / unit area]
n_particles_list = np.array([100, 200, 400, 800, 1600])
all_pair_checks, cell_cand_checks = [], []
print(f"{'N':>6s} | {'Box L':>7s} | {'True Pairs':>10s} | {'All-Pairs N(N-1)/2':>18s} | {'Cell-List Checks':>16s} | {'Speedup':>9s}")
print("-" * 80)
for n_p in n_particles_list:
box_l = math.sqrt(n_p / density_rho)
pts = rng_cl.uniform(0.0, box_l, size=(int(n_p), 2))
cl_res = invariants_complexity.spatial_cell_list_neighbors(pts, cutoff_rc)
if n_p <= 400:
bf_pairs = invariants_complexity.brute_force_neighbors(pts, cutoff_rc)
assert cl_res["pairs"] == bf_pairs # Exact bit-for-bit sorted pair list match
all_pair_checks.append(cl_res["all_pairs_count"])
cell_cand_checks.append(cl_res["candidate_distance_checks"])
print(f"{int(n_p):6d} | {box_l:7.2f} | {cl_res['n_pairs']:10,d} | {cl_res['all_pairs_count']:18,d} | "
f"{cl_res['candidate_distance_checks']:16,d} | {cl_res['speedup_over_all_pairs']:8.1f}x")
fit_bf = invariants_complexity.fit_empirical_complexity(n_particles_list, np.array(all_pair_checks))
fit_cl = invariants_complexity.fit_empirical_complexity(n_particles_list, np.array(cell_cand_checks))
print(f"\nEmpirical scaling: Brute-Force p = {fit_bf['exponent_p']:.3f} ({fit_bf['complexity_class']}) vs Cell-List p = {fit_cl['exponent_p']:.3f} ({fit_cl['complexity_class']})")
fig, ax = plt.subplots(figsize=(7.6, 4.1))
ax.loglog(n_particles_list, all_pair_checks, "o-", color="#C0392B", lw=2.2, label=f"All-pairs brute force (p = {fit_bf['exponent_p']:.2f})")
ax.loglog(n_particles_list, cell_cand_checks, "s--", color="#2166AC", lw=2.2, label=f"Uniform cell-list stencil (p = {fit_cl['exponent_p']:.2f})")
ax.set_xlabel("Number of particles $N$ (at constant density $\\rho_0$)")
ax.set_ylabel("Pairwise distance evaluations")
ax.set_title("Cell lists against all pairs")
ax.legend(fontsize=8.5)
plt.show()
assert fit_bf["complexity_class"] == "O(N^2)" and fit_cl["complexity_class"] == "O(N)"
assert cell_cand_checks[-1] * 50 < all_pair_checks[-1]
Demonstration 4: Spatial cell-list hashing O(N) against brute-force all-pairs O(N^2)
====================================================================================
N | Box L | True Pairs | All-Pairs N(N-1)/2 | Cell-List Checks | Speedup
--------------------------------------------------------------------------------
100 | 11.18 | 174 | 4,950 | 476 | 10.4x
200 | 15.81 | 385 | 19,900 | 1,051 | 18.9x
400 | 22.36 | 772 | 79,800 | 2,118 | 37.7x
800 | 31.62 | 1,581 | 319,600 | 4,310 | 74.2x
1600 | 44.72 | 3,153 | 1,279,200 | 8,765 | 145.9x
Empirical scaling: Brute-Force p = 2.003 (O(N^2)) vs Cell-List p = 1.044 (O(N))

Figure 3.3. Neighbour search at constant density: the number of pairwise distance evaluations against the number of particles. All pairs grow with exponent 2.00; the cell list grows with exponent 1.04.
Inside the algorithm¶
We inspect invariants_complexity.sliding_window_max_monotonic_deque and invariants_complexity.spatial_cell_list_neighbors, and implement another classic amortized workhorse: Caterpillar / Two-Pointer Sliding Energy Window (two_pointer_subarray_energy_bound), finding the longest contiguous sensor interval whose integrated non-negative power in pointer advances instead of subarray scans.
Check against the library¶
heading("Inside the algorithm: Monotonic deque, cell lists and two-pointer energy-bounded subarray")
print(show_source(invariants_complexity.sliding_window_max_monotonic_deque))
print(show_source(invariants_complexity.spatial_cell_list_neighbors))
def two_pointer_subarray_energy_bound(power_arr: np.ndarray, max_energy: float) -> dict:
"""Find max-length contiguous subarray [left, right] with sum <= max_energy on non-negative array in O(N)."""
p = np.asarray(power_arr, dtype=float).ravel()
if np.any(p < 0.0) or max_energy < 0.0:
raise ValueError("Non-negativity of power_arr is the structural invariant enabling monotone two-pointer advance")
left = 0
window_sum = 0.0
best_len = 0
best_span = (0, -1)
pointer_moves = 0
for right in range(p.size):
window_sum += float(p[right])
pointer_moves += 1
while window_sum > max_energy and left <= right:
window_sum -= float(p[left])
left += 1
pointer_moves += 1
cur_len = right - left + 1
if cur_len > best_len:
best_len = cur_len
best_span = (left, right)
return {"max_length": best_len, "best_span": best_span, "pointer_moves": pointer_moves}
rng_tp = np.random.default_rng(31)
p_trace = rng_tp.uniform(0.5, 4.5, size=350)
e_cap = 42.0
tp_res = two_pointer_subarray_energy_bound(p_trace, e_cap)
# Verify against exact O(N^2) brute-force oracle:
bf_best = 0
for i in range(p_trace.size):
s = 0.0
for j in range(i, p_trace.size):
s += float(p_trace[j])
if s <= e_cap:
bf_best = max(bf_best, j - i + 1)
else:
break
print(f"Two-Pointer max burst length = {tp_res['max_length']} (span {tp_res['best_span']}) in {tp_res['pointer_moves']} moves (<= 2N = {2*p_trace.size})")
assert tp_res["max_length"] == bf_best
assert tp_res["pointer_moves"] <= 2 * p_trace.size
Inside the algorithm: Monotonic deque, cell lists and two-pointer energy-bounded subarray
=========================================================================================
def sliding_window_max_monotonic_deque(values: np.ndarray, window_k: int) -> dict:
"""Compute all N - k + 1 sliding-window maxima in strictly O(N) via a decreasing monotonic deque invariant."""
arr = np.asarray(values, dtype=float).ravel()
k = int(window_k)
if k < 1 or k > arr.size:
raise ValueError("Require 1 <= window_k <= len(values).")
dq: deque[int] = deque()
out = np.empty(arr.size - k + 1, dtype=float)
pushes = 0
pops = 0
comps = 0
for i in range(arr.size):
while dq and dq[0] <= i - k:
dq.popleft()
pops += 1
while dq:
comps += 1
if arr[dq[-1]] <= arr[i]:
dq.pop()
pops += 1
else:
break
dq.append(i)
pushes += 1
if i >= k - 1:
out[i - k + 1] = arr[dq[0]]
return {
"window_maxima": out,
"total_pushes": pushes,
"total_pops": pops,
"element_comparisons": comps,
}
def spatial_cell_list_neighbors(coords: np.ndarray, cutoff_r: float) -> dict:
"""Find all 2-D pairs within Euclidean cutoff_r in O(N) expected time using uniform cell-list hashing."""
pts = np.asarray(coords, dtype=float)
if pts.ndim != 2 or pts.shape[1] != 2 or cutoff_r <= 0.0:
raise ValueError("Require (N, 2) coords and cutoff_r > 0.")
n = pts.shape[0]
h = float(cutoff_r)
r2 = h * h
buckets: dict[tuple[int, int], list[int]] = {}
for idx in range(n):
cx = math.floor(pts[idx, 0] / h)
cy = math.floor(pts[idx, 1] / h)
buckets.setdefault((cx, cy), []).append(idx)
# Half-stencil + self-cell avoids duplicate pair tests while visiting every neighbor pair exactly once:
half_offsets = [(0, 1), (1, -1), (1, 0), (1, 1)]
pairs: list[tuple[int, int]] = []
cand_checks = 0
for (cx, cy), members in buckets.items():
m = len(members)
for a in range(m):
i = members[a]
for b in range(a + 1, m):
j = members[b]
cand_checks += 1
dx = pts[i, 0] - pts[j, 0]
dy = pts[i, 1] - pts[j, 1]
if dx * dx + dy * dy <= r2:
pairs.append((i, j) if i < j else (j, i))
for dx_c, dy_c in half_offsets:
nbrs = buckets.get((cx + dx_c, cy + dy_c))
if nbrs is None:
continue
for i in members:
for j in nbrs:
cand_checks += 1
dx = pts[i, 0] - pts[j, 0]
dy = pts[i, 1] - pts[j, 1]
if dx * dx + dy * dy <= r2:
pairs.append((i, j) if i < j else (j, i))
pairs.sort()
all_pairs = n * (n - 1) // 2
return {
"pairs": pairs,
"n_pairs": len(pairs),
"candidate_distance_checks": cand_checks,
"all_pairs_count": all_pairs,
"speedup_over_all_pairs": (all_pairs / max(1, cand_checks)) if all_pairs > 0 else 1.0,
}
Two-Pointer max burst length = 24 (span (309, 332)) in 682 moves (<= 2N = 700)
Exercises¶
Worked solutions are in 03_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify Tarjan’s exact potential telescoping identity
total_pushes - total_pops == final_deque_len >= 1andtotal_pushes + total_pops <= 2*N - 1oninvariants_complexity.sliding_window_max_monotonic_dequeacross strictly increasing, strictly decreasing, sawtooth, and impulse signals ().Find how it fails. 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 .Implement it yourself. Implement
largest_zero_defect_rectangle_histogram(heights)using an increasing monotonic stack in strictly time (pushes == N + 1including sentinel0,pops <= N), returningmax_area,best_span(left_idx, right_idx_exclusive, height),pushes, andpops. Verify exact equality against an brute-force oracle on 40 random and structured histograms.
heading("Self-check for the exercises")
assert np.allclose(sat_res["sums"], oracle_sums, rtol=1e-12)
assert fit_bf["complexity_class"] == "O(N^2)" and fit_cl["complexity_class"] == "O(N)"
assert tp_res["max_length"] == bf_best
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.