Solutions · 4. Divide and conquer: recursion trees, binary search on the answer and inversion counting
Worked solutions to the three exercises of Lecture 4. 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: Empirical verification of all three master-theorem regimes")
def eval_recurrence_work(n: int, a: int, b: int, d: int) -> float:
"""Exact work count of T(N) = a * T(N // b) + N^d with base T(1) = 1."""
if n <= 1:
return 1.0
return a * eval_recurrence_work(n // b, a, b, d) + float(n ** d)
n_pows = np.array([2 ** k for k in range(4, 13)], dtype=float)
cases = [
("Root-dominated (a=1, b=2, d=1 -> O(N))", 1, 2, 1, "O(N)"),
("Balanced tree (a=2, b=2, d=1 -> O(N log N))", 2, 2, 1, "O(N log N)"),
("Karatsuba split (a=3, b=2, d=1 -> O(N^1.585))", 3, 2, 1, "O(N^2)"),
("Leaf-dominated (a=4, b=2, d=1 -> O(N^2))", 4, 2, 1, "O(N^2)"),
]
fig, ax = plt.subplots(figsize=(7.8, 4.2))
for label, a_c, b_c, d_c, _ in cases:
w_vals = np.array([eval_recurrence_work(int(n_v), a_c, b_c, d_c) for n_v in n_pows])
fit_r = invariants_complexity.fit_empirical_complexity(n_pows, w_vals)
theo_exp = max(float(d_c), math.log(a_c, b_c))
print(f"{label:46s} | Fitted p = {fit_r['exponent_p']:.3f} | Master max(d, log_b a) = {theo_exp:.3f}")
ax.loglog(n_pows, w_vals, "o-", lw=2.0, label=f"{label.split('->')[0].strip()} (p={fit_r['exponent_p']:.2f})")
if a_c != b_c ** d_c:
assert abs(fit_r["exponent_p"] - theo_exp) < 0.06
ax.set_xlabel("Problem size $N = 2^k$")
ax.set_ylabel("Total recursion-tree work $T(N)$")
ax.set_title("Three regimes of the master theorem")
ax.legend(fontsize=8.0)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify the exact identity using divide_spatial.mergesort_with_inversions against concordant/discordant pair counting across identity (), reverse (), and 30 random permutations of distinct sensors.
heading("Exercise 1: Exact Kendall-tau rank correlation in O(N log N) via MergeSort inversions")
def kendall_tau_mergesort(rank_x: np.ndarray, rank_y: np.ndarray) -> float:
"""Compute exact Kendall tau for two rankings without ties in O(N log N)."""
order_x = np.argsort(rank_x)
y_aligned = np.asarray(rank_y, dtype=float)[order_x]
n = y_aligned.size
inv = divide_spatial.mergesort_with_inversions(y_aligned)["inversions"]
return 1.0 - (4.0 * inv) / (n * (n - 1))
def kendall_tau_brute_oracle(rank_x: np.ndarray, rank_y: np.ndarray) -> float:
n = rank_x.size
conc, disc = 0, 0
for i in range(n):
for j in range(i + 1, n):
s = (rank_x[i] - rank_x[j]) * (rank_y[i] - rank_y[j])
if s > 0:
conc += 1
elif s < 0:
disc += 1
return (conc - disc) / (0.5 * n * (n - 1))
n_kt = 80
base_r = np.arange(n_kt, dtype=float)
assert kendall_tau_mergesort(base_r, base_r) == 1.0
assert kendall_tau_mergesort(base_r, base_r[::-1]) == -1.0
rng_kt = np.random.default_rng(61)
taus = []
for _ in range(30):
rx = rng_kt.permutation(n_kt).astype(float)
ry = rng_kt.permutation(n_kt).astype(float)
t_fast = kendall_tau_mergesort(rx, ry)
t_slow = kendall_tau_brute_oracle(rx, ry)
taus.append(t_fast)
assert abs(t_fast - t_slow) < 1.0e-15
print(f"Verified 30 random N={n_kt} permutations to < 1e-15 Sample mean E[tau] = {np.mean(taus):+.4f} (theory = 0.0000)")
Exercise 1: Exact Kendall-tau rank correlation in O(N log N) via MergeSort inversions
=====================================================================================
Verified 30 random N=80 permutations to < 1e-15 Sample mean E[tau] = -0.0041 (theory = 0.0000)
Explanation. Permuting both arrays so leaves every pair’s concordance unchanged while forcing for all . Consequently, pair is discordant () iff (an inversion) and concordant () otherwise, giving .
Exercise 2¶
Problem. Demonstrate (a) how parametric_binary_search_min fails silently on a non-monotone rotor resonance predicate over with resonance peaks near 35 and 78 rad/s (the search misses the unsafe band around 78 rad/s), and (b) how changing <= to < in MergeSort fabricates fake inversions on a constant sensor vector.
heading("Exercise 2: Audit of non-monotone resonance trap and strict `<` MergeSort tie corruption")
# (a) Synthetic rotor vibration amplitude [mm] with two resonance peaks, near 35 and 78 rad/s: the predicate is False, True, False, True along the speed axis.
def bimodal_safe(omega: float) -> bool:
r1 = 5.0 * math.exp(-((omega - 35.0) / 6.0) ** 2)
r2 = 3.5 * math.exp(-((omega - 78.0) / 3.5) ** 2)
return (0.5 + r1 + r2) <= 2.0
# The lowest speed above which the rotor stays safe up to 100 rad/s is about 81.7 rad/s
bs_wrong = divide_spatial.parametric_binary_search_min(bimodal_safe, lo=35.0, hi=100.0, tol=1e-6)
grid_w = np.linspace(35.0, 100.0, 2000)
unsafe_above_reported = [float(w) for w in grid_w if w > bs_wrong["threshold"] and not bimodal_safe(float(w))]
print(f"(a) Parametric binary search reported threshold = {bs_wrong['threshold']:.2f} rad/s,")
print(f" yet {len(unsafe_above_reported)} supercritical speeds above {bs_wrong['threshold']:.1f} rad/s (around 78 rad/s) are unsafe")
# (b) MergeSort with strict `<` instead of `<=` on identical values [5.0, 5.0, ..., 5.0]:
def buggy_strict_lt_inversions(values: list[float]) -> int:
inv = [0]
def _ms(sub: list[float]) -> list[float]:
if len(sub) <= 1:
return sub
mid = len(sub) // 2
left, right = _ms(sub[:mid]), _ms(sub[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]: # <-- BUG: ties take the `else` branch and count as inversions
out.append(left[i]); i += 1
else:
out.append(right[j]); inv[0] += len(left) - i; j += 1
return out + left[i:] + right[j:]
_ms(values)
return inv[0]
const_8 = [5.0] * 8
fake_inv = buggy_strict_lt_inversions(const_8)
true_inv = divide_spatial.mergesort_with_inversions(np.array(const_8))["inversions"]
print(f"\n(b) Constant array [5.0]*8: True inversions = {true_inv} vs Buggy `<` MergeSort = {fake_inv} (= 8*7/2 = 28)")
assert len(unsafe_above_reported) > 50
assert true_inv == 0 and fake_inv == 8 * 7 // 2
Exercise 2: Audit of non-monotone resonance trap and strict `<` MergeSort tie corruption
========================================================================================
(a) Parametric binary search reported threshold = 41.58 rad/s,
yet 198 supercritical speeds above 41.6 rad/s (around 78 rad/s) are unsafe
(b) Constant array [5.0]*8: True inversions = 0 vs Buggy `<` MergeSort = 28 (= 8*7/2 = 28)
Explanation. Binary-searching the answer relies entirely on the monotonicity implication for all ; when multiple resonant modes create False -> True -> False -> True islands, mid = 67.5 evaluates True and discards [67.5, 100], hiding the second critical speed at . In MergeSort, equal elements () are not inversions and must be emitted from left first (<=) to preserve stability.
Exercise 3¶
Problem. Implement min_relay_radius_connected(coords, max_hops) using BFS from gateway station 0 inside divide_spatial.parametric_binary_search_min on constants_benchmarks.make_sensor_station_coords(n_stations=50, seed=42). Verify monotonically decreasing across max_hops in [1, 2, 3, 4, 6, 49], cross-check against exact discrete pairwise distance binary search, and plot the 4-hop radio relay tree.
heading("Exercise 3: Implement it yourself — minimum multi-hop radio relay radius (BFS + parametric search)")
from collections import deque
def _can_reach_all_within_hops(dist_mat: np.ndarray, radius: float, max_hops: int) -> tuple[bool, list[tuple[int, int]]]:
n = dist_mat.shape[0]
visited = [False] * n
visited[0] = True
q: deque[tuple[int, int]] = deque([(0, 0)])
tree_edges: list[tuple[int, int]] = []
reached = 1
while q:
u, d_hop = q.popleft()
if d_hop >= max_hops:
continue
for v in range(n):
if not visited[v] and dist_mat[u, v] <= radius:
visited[v] = True
reached += 1
tree_edges.append((u, v))
q.append((v, d_hop + 1))
return reached == n, tree_edges
def min_relay_radius_connected(coords: np.ndarray, max_hops: int) -> dict:
"""Find minimum radio range [km] connecting all stations to gateway 0 in <= max_hops via parametric search."""
pts = np.asarray(coords, dtype=float)
if pts.ndim != 2 or pts.shape[1] != 2 or max_hops < 1:
raise ValueError("Require (N, 2) coords and max_hops >= 1.")
diff = pts[:, None, :] - pts[None, :, :]
dist_mat = np.hypot(diff[:, :, 0], diff[:, :, 1])
hi_bound = float(np.max(dist_mat))
res = divide_spatial.parametric_binary_search_min(
lambda r: _can_reach_all_within_hops(dist_mat, r, max_hops)[0],
lo=0.0,
hi=hi_bound,
tol=1.0e-9,
)
# Cross-check against exact sorted pairwise distances via integer parametric binary search:
uniq_dists = np.unique(dist_mat)
int_res = divide_spatial.parametric_binary_search_int(
lambda idx: _can_reach_all_within_hops(dist_mat, float(uniq_dists[idx]), max_hops)[0],
lo=0,
hi=uniq_dists.size - 1,
)
exact_edge_r = float(uniq_dists[int_res["threshold"]])
_, edges = _can_reach_all_within_hops(dist_mat, exact_edge_r, max_hops)
return {
"min_radius_km": res["threshold"],
"exact_edge_radius_km": exact_edge_r,
"evaluations": res["evaluations"],
"bfs_tree_edges": edges,
}
stations = constants_benchmarks.make_sensor_station_coords(n_stations=50, seed=42)
hop_budgets = [1, 2, 3, 4, 6, 49]
radii_by_hops = []
for h_b in hop_budgets:
out_h = min_relay_radius_connected(stations, h_b)
radii_by_hops.append(out_h["min_radius_km"])
print(f"max_hops = {h_b:2d} -> R_min = {out_h['min_radius_km']:8.4f} km (exact pairwise edge = {out_h['exact_edge_radius_km']:8.4f} km)")
assert abs(out_h["min_radius_km"] - out_h["exact_edge_radius_km"]) < 1.0e-7
mesh_4 = min_relay_radius_connected(stations, max_hops=4)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.2))
for u_i, v_i in mesh_4["bfs_tree_edges"]:
ax1.plot([stations[u_i, 0], stations[v_i, 0]], [stations[u_i, 1], stations[v_i, 1]], "-", color="#2166AC", lw=1.2, alpha=0.75)
ax1.scatter(stations[1:, 0], stations[1:, 1], color="#2E8B57", s=35, zorder=4, label="Field sensors (1..49)")
ax1.scatter([stations[0, 0]], [stations[0, 1]], color="#C0392B", marker="*", s=150, zorder=5, label="Gateway hub 0")
ax1.set_xlabel("East coordinate $x$ [km]")
ax1.set_ylabel("North coordinate $y$ [km]")
ax1.set_title(f"Optimal 4-hop relay tree ($R_{{\\min}} = {mesh_4['min_radius_km']:.2f}$ km)")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.0)
ax2.plot(hop_budgets, radii_by_hops, "o-", color="#C0392B", lw=2.1)
ax2.set_xlabel("Maximum allowed radio hops")
ax2.set_ylabel(r"Minimum required radio range $R_{\min}$ [km]")
ax2.set_title("Multi-hop relaying lowers the required range")
label_panels(fig)
plt.show()
assert all(radii_by_hops[i] >= radii_by_hops[i + 1] - 1e-9 for i in range(len(radii_by_hops) - 1))
assert radii_by_hops[-1] < 0.35 * radii_by_hops[0]
Exercise 3: Implement it yourself — minimum multi-hop radio relay radius (BFS + parametric search)
==================================================================================================
max_hops = 1 -> R_min = 88.3286 km (exact pairwise edge = 88.3286 km)
max_hops = 2 -> R_min = 45.1535 km (exact pairwise edge = 45.1535 km)
max_hops = 3 -> R_min = 32.4729 km (exact pairwise edge = 32.4729 km)
max_hops = 4 -> R_min = 27.8464 km (exact pairwise edge = 27.8464 km)
max_hops = 6 -> R_min = 20.3714 km (exact pairwise edge = 20.3714 km)
max_hops = 49 -> R_min = 16.7034 km (exact pairwise edge = 16.7034 km)

Figure S4.1. Multi-hop relay radius. (a) The breadth-first tree that connects all 50 stations to the gateway within 4 hops at . (b) against the hop budget.
Summary. The threshold is always one of the pairwise distances. Continuous bisection with parametric_binary_search_min approaches it to within its tolerance, while bisection over the sorted distances with parametric_binary_search_int finds the critical link exactly in BFS runs. Going from one hop to four lowers from 88.3 km to 27.8 km; if the transmitter power scales as (an assumption, as in free space), that is a factor of about 10 in power.