Lawfare Academy

CS 201 — Data Structures, Algorithms and Systems · Weeks 15–16

Systems, resource budgets and an integrated comparison

Full teaching sequence and cumulative subject work

Preparation: study Chapter reviews 1–4: cumulative proof and structure comparison in the complete on-site Levin text. Attempt the investigation, work at least four exercises of increasing difficulty in each assigned section, and compare the selected hints/solutions only after a written attempt. Then complete the algorithm reading and implement the unit laboratory. For each algorithm give a specification, trace, correctness argument and time/space analysis.

Weighted shortest paths: implementation, proof and complexity — primary material, constructed-response tasks, complete worked model and changed-case examination →

Streaming state and a defensible comparison

A resource budget includes input storage, auxiliary state, output and transient copies. An iterator-based aggregate may hold little auxiliary state, yet its caller may already have materialized the entire input. A benchmark must identify which costs are included. Reusing an exhausted iterator can make a second algorithm appear artificially fast because it processes no records.

Measure correctness before performance. Use the same logical records, reset the input for every run, count operations where possible and report distributions rather than one favorable time. For memory, distinguish a constant running total from per-customer state that grows with the number of distinct customers.

Worked problem

A generator produces one million transactions. Method A sums it, then Method B indexes the same generator and reports a tiny runtime and zero customers. Evaluate the comparison.

Trace the complete reasoning
  1. A consumes the iterator. B receives no remaining records, so its output fails the shared logical-input requirement.

  2. Recreate the generator from the same deterministic source for each method. Verify count and total before comparing runtime.

  3. An overall total uses constant aggregate state; an index needs storage proportional to represented keys and records, depending on its output contract.

  4. Include construction costs, query volume and update workload. One timing cannot establish an asymptotic law or a universal winner.

Independent transfer problem

The application only needs the five largest customer totals. Can it always use constant memory while reading unsorted transactions? Explain what must be retained or moved elsewhere.

Compare the transfer solution

Exact arbitrary customer totals generally require state for customers that may reappear later. Keeping only the current five can discard a customer whose later transactions make it the largest. Aggregate by customer in a mapping, external sort, or database, then select five totals. A fixed-size top-five heap helps after complete customer totals exist; it does not eliminate the grouping requirement.

Learning objectives

  • Explain and trace the mechanisms in systems, resource budgets and an integrated comparison.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Study the mechanism

Programs execute within systems that impose resource limits and failure modes. A process has memory and execution state; files provide persistence; network requests can fail independently of local calculation. Moving data between components has a cost. An asymptotically efficient algorithm can still be impractical if it repeatedly serializes huge records or holds unnecessary copies.

Separate latency, throughput and memory. Latency is time for one operation; throughput is operations per unit time under specified load. Increasing concurrency can improve throughput until another bottleneck dominates, while worsening tail latency. Report input sizes, repetitions, measurement method and variability. A single fastest timing is poor evidence. Verify outputs before comparing speed, because removing validation can make an incorrect program look faster.

Resource budgets are design constraints. If an in-memory index exceeds available memory, an on-disk database or streaming strategy may be preferable. Streaming can compute totals without storing every row, but cannot answer arbitrary later queries unless it maintains sufficient state or rereads the data. Explain what information a summary discards. Resilience requires understanding interruption: a crash between changing a source record and updating its index can violate consistency. Rebuildable indexes and transactional storage address different parts of this problem.

Worked example

def streaming_total(rows):
    count = 0
    cents = 0
    for row in rows:
        count += 1
        cents += row["cents"]
    return count, cents

assert streaming_total(iter([
    {"cents": 100}, {"cents": -20}])) == (2, 80)

The loop holds aggregate state rather than all rows, so its auxiliary state is small. It consumes an iterator; callers cannot assume that the same iterator still yields those rows afterward. The total deliberately discards per-customer detail. If later queries require customer totals, maintain a customer mapping whose size grows with distinct customers or use persistent storage.

Check your understanding

What should a defensible benchmark compare first?

  1. Equivalent specified behavior and correct outputs
  2. Only the fastest observed run
  3. Implementations with validation removed from one side
Answer and reasoning for every option

Correct: Equivalent specified behavior and correct outputs Timing is meaningful only for comparable correct work.

Reconsider: Only the fastest observed run A selected best run can hide variability and setup costs.

Reconsider: Implementations with validation removed from one side Unequal responsibilities invalidate the comparison.

Transfer laboratory: Streaming and an impossible future query

A pipeline keeps only total cents and count. A user later asks for the median and each customer’s balance. Can the pipeline answer exactly without rereading or additional retained state?

Work through the full solution

No. Many different datasets have the same sum and count but different medians and customer balances. The retained summary discards information needed for those questions. Preserve suitable order statistics or per-customer aggregates, use external storage, or reread the source. More sophisticated code cannot reconstruct uniquely discarded information.

Evidence of understanding

Give two datasets with equal sum/count and different medians, and state the required extra data.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 13 . Data Structures for Integers · Pat Morin
  2. 13 . 1 BinaryTrie: A digital search tree · Pat Morin
  3. 13 . 2 XFastTrie: Searching in Doubly-Logarithmic Time · Pat Morin
  4. 13 . 3 YFastTrie: A Doubly-Logarithmic Time SSet · Pat Morin
  5. 13 . 4 Discussion and Exercises · Pat Morin
  6. 14 . External Memory Searching · Pat Morin
  7. 14 . 1 The Block Store · Pat Morin
  8. 14 . 2 B-Trees · Pat Morin
  9. 14 . 3 Discussion and Exercises · Pat Morin

Open in My Learning to record progress →