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.

3. Measuring cost: doubling ratios, prefix sums, monotonic queues and cell lists

School of Engineering, Nazarbayev University

When a laboratory data pipeline takes 10 minutes to process N=100,000N = 100{,}000 particles or infrared frames, the first idea is often to rewrite the loops in C++ or to rent a GPU. If the algorithm is O(N2)\mathcal{O}(N^2), however, going to N=107N = 10^7 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

  1. Diagnose empirical time/operation complexity C(N)∼aNpC(N) \sim a N^p via log-log slopes and doubling ratios C(2N)/C(N)→2pC(2N)/C(N) \to 2^p using invariants_complexity.fit_empirical_complexity.

  2. Evaluate arbitrary 2-D rectangular flux integrals in strictly 4 array lookups (O(1)\mathcal{O}(1) per query) via inclusion–exclusion in invariants_complexity.prefix_sum_2d_integral.

  3. Compute all sliding-window maxima of width kk in strictly ≤2N\le 2N amortized deque operations (independent of kk) using invariants_complexity.sliding_window_max_monotonic_deque.

  4. Accelerate 2-D short-range particle neighbor discovery from O(N2)\mathcal{O}(N^2) to O(N)\mathcal{O}(N) expected time via invariants_complexity.spatial_cell_list_neighbors, verified against brute_force_neighbors.

Time: about 60 min

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 C(N)C(N) across geometric doublings N,2N,4N,…N, 2N, 4N, \dots. If C(N)≈aNpC(N) \approx a N^p, doubling NN multiplies cost by a constant ratio:

C(2N)C(N)⟶2p  ⟹  plocal(N)=log⁡2C(2N)C(N)(1.1)\frac{C(2N)}{C(N)} \longrightarrow 2^p \implies p_{\mathrm{local}}(N) = \log_2 \frac{C(2N)}{C(N)} \tag{1.1}

A ratio near 1.0 signals O(1)\mathcal{O}(1) or O(log⁡N)\mathcal{O}(\log N); 2.0 signals O(N)\mathcal{O}(N) (or 2.0+ϵ2.0 + \epsilon for O(Nlog⁡N)\mathcal{O}(N \log N)); 4.0 signals O(N2)\mathcal{O}(N^2); and 8.0 signals O(N3)\mathcal{O}(N^3).


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 size 1265x462 with 2 Axes>

Figure 3.1. Doubling-ratio diagnostics for five synthetic cost laws. (a) Operation counts C(N)C(N) on log-log axes. (b) The local exponent log⁡2[C(2N)/C(N)]\log_2[C(2N)/C(N)]: it settles at 0, 1 and 2 for constant, linear and quadratic cost, decreases slowly towards 0 for log⁡N\log N, and stays a little above 1 for Nlog⁡NN \log N.

What Demonstration 1 shows.

  • At N=4,096N = 4{,}096, All-pairs quadratic already executes 8.39×1068.39 \times 10^6 operations vs. 10,24010{,}240 for Single linear scan (819×819\times slower), and every subsequent 10×10\times increase in sensor resolution widens that gap by another factor of 10.


2. Summed-Area Prefix Integrals for O(1)\mathcal{O}(1) Rectangular Queries (prefix_sum_2d_integral)

Suppose an infrared thermography camera captures an H×WH \times W heat-flux map qr,c [W/m2]q_{r,c}\,[\mathrm{W/m^2}] across a battery module, and a thermal controller evaluates Q=1,000Q = 1{,}000 candidate cooling-zone rectangles [r0,r1]×[c0,c1][r_0, r_1] \times [c_0, c_1]. Summing each subarray naively takes O(QHW)\mathcal{O}(Q H W) additions. Mental Move #8, Precompute Prefix Integrals for O(1)\mathcal{O}(1) Queries (Crow 1984; Viola–Jones 2001) builds the (H+1)×(W+1)(H+1)\times(W+1) cumulative table Pr,c=∑i<r∑j<cqi,jP_{r,c} = \sum_{i < r}\sum_{j < c} q_{i,j} once in O(HW)\mathcal{O}(H W) and answers any rectangle of any size in exactly 4 table lookups via inclusion–exclusion:

∑r=r0r1∑c=c0c1qr,c=Pr1+1, c1+1−Pr0, c1+1−Pr1+1, c0+Pr0, c0(2.1)\sum_{r=r_0}^{r_1}\sum_{c=c_0}^{c_1} q_{r,c} = P_{r_1+1,\,c_1+1} - P_{r_0,\,c_1+1} - P_{r_1+1,\,c_0} + P_{r_0,\,c_0} \tag{2.1}

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 1,0001{,}000 queries on a 120×120120 \times 120 sensor array, inclusion–exclusion reduces the arithmetic by a factor of 92 (the queries alone fall from 1.69×1061.69 \times 10^6 cell reads to 4,0004{,}000 lookups, a factor of about 420).


3. Amortized O(N)\mathcal{O}(N) Sliding-Window Maxima via Monotonic Deques (sliding_window_max_monotonic_deque)

To detect transient overpressure envelopes over a rolling window of width kk across NN samples, np.array([np.max(x[i:i+k]) for i in range(N-k+1)]) performs (N−k+1)(k−1)∼O(Nk)(N - k + 1)(k - 1) \sim \mathcal{O}(N k) comparisons, taking quadratic O(N2)\mathcal{O}(N^2) work when k∝Nk \propto N.

Mental Move #9, Prune Dominated Candidates in a Monotonic Queue: Suppose index j<ij < i is still inside the current window, and the newly arrived sample satisfies xj≤xix_j \le x_i. Because xjx_j is both older (expires sooner) and smaller than xix_i, xjx_j 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 O(1)\mathcal{O}(1). Because each index i∈{0,…,N−1}i \in \{0, \dots, N-1\} enters the deque once and leaves at most once, total pushes + pops is bounded by 2N2N for ANY window width kk.


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 size 1265x451 with 2 Axes>

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 kk: the naive scan grows as NkN k, the monotonic deque stays below 2N2N for every kk.

  • At k=2,500k = 2{,}500, naive scanning performs 8.75×1068.75 \times 10^6 comparisons while the monotonic deque performs 11,98911{,}989, a reduction by a factor of 730, with identical output. The deque’s count stays below 2N=12,0002N = 12{,}000 for every window width.


4. Spatial Cell-List Hashing Reduces All-Pairs O(N2)\mathcal{O}(N^2) into O(N)\mathcal{O}(N) (spatial_cell_list_neighbors)

In molecular dynamics (Lennard-Jones cutoff rcr_c), smoothed-particle hydrodynamics (SPH), and granular DEM contact detection, only particle pairs within Euclidean distance rij≤rcr_{ij} \le r_c interact. Testing all (N2)=N(N−1)/2\binom{N}{2} = N(N-1)/2 pairs spends almost all the work on distant particles: at N=1600N = 1600 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 h=rch = r_c via integer floor hashing (cx,cy)=(⌊x/rc⌋,⌊y/rc⌋)(c_x, c_y) = (\lfloor x/r_c \rfloor, \lfloor y/r_c \rfloor). Any neighbor within distance rcr_c of a particle in cell (cx,cy)(c_x, c_y) must reside in (cx,cy)(c_x, c_y) 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 ρ0=N/L2\rho_0 = N / L^2, each cell holds mˉ=ρ0rc2=O(1)\bar{m} = \rho_0 r_c^2 = \mathcal{O}(1) particles, reducing total distance checks to strictly O(N)\mathcal{O}(N).


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 size 836x451 with 1 Axes>

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 O(N)\mathcal{O}(N) workhorse: Caterpillar / Two-Pointer Sliding Energy Window (two_pointer_subarray_energy_bound), finding the longest contiguous sensor interval whose integrated non-negative power ∑t=lrPt≤Emax⁡\sum_{t=l}^r P_t \le E_{\max} in ≤2N\le 2N pointer advances instead of O(N2)\mathcal{O}(N^2) subarray scans.

Check against the library


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.

  1. Verify a result. 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 (N=3000,k=200N = 3000, k = 200).

  2. Find how it fails. Quantify (a) exact element-shift operations in list.pop(0) vs. deque.popleft() across N∈[500,1000,2000,4000]N \in [500, 1000, 2000, 4000], and (b) silent false-negative neighbor misses when a 3×33 \times 3 cell-list search uses an undersized cell width h=0.5 rch = 0.5\,r_c.

  3. Implement it yourself. Implement largest_zero_defect_rectangle_histogram(heights) using an increasing monotonic stack in strictly O(N)\mathcal{O}(N) 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 O(N2)\mathcal{O}(N^2) brute-force oracle on 40 random and structured histograms.


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