foundation16 min studyLesson 2 in Engineering

Algorithms: count the work before buying capacity

Reason about correctness, growth rates, and the difference between an asymptotic bound and a latency measurement.

On this page

What you’ll understand

  • Describe an algorithm's inputs, outputs, and correctness condition.
  • Compare linear, logarithmic, and quadratic growth.
  • Combine complexity analysis with representative benchmarking.

An algorithm is a reproducible method for turning inputs into an answer. Before optimizing it, specify what a correct answer means. Infrastructure capacity cannot rescue an algorithm whose required work grows faster than the workload budget. Complexity gives a language for that growth, while measurements reveal the constants and machine effects that the language deliberately leaves out.

Specify the problem before the procedure

Consider finding a request ID in a collection. Does the collection contain duplicates? Must the result include every match, the first match, or simply a yes-or-no answer? Is the input sorted, and who pays to keep it sorted? These choices change both correctness and cost. A fast method that silently relies on an absent ordering property is an incorrect method, not an optimization with an unusual edge case.

An invariant is a statement maintained as an algorithm proceeds. A linear search can maintain that all earlier items have been inspected without finding a match. Binary search maintains a smaller interval that contains any remaining possible match. Writing the invariant helps explain why the answer is justified and why the loop terminates. It also suggests tests for empty input, one element, duplicate boundaries, and missing targets.

Clinear(n)≤n,Cbinary(n)≤⌈log⁡2(n+1)⌉C_{\rm linear}(n)\leq n,\qquad C_{\rm binary}(n)\leq\lceil\log_2(n+1)\rceil
These are bounds for linear search and binary search over sorted random-access data, counting one three-way item comparison per inspected position. n counts items; comparisons are dimensionless work units, not seconds.↔ Scroll wide equations horizontally.

Growth rates expose scaling pressure

Big-O describes an upper growth bound as input size becomes large. It does not say that every operation has equal cost, or that one implementation is faster at every size. A quadratic all-pairs comparison examines a number of pairs proportional to the square of the input size. Doubling the size can approximately quadruple that work. A linear pass approximately doubles its work under the same change.

Do not confuse average behavior with a worst-case guarantee. A lookup structure can perform well for representative keys while still having expensive exceptional cases or resize events. Memory usage and preprocessing are part of the tradeoff: building an index has a cost that may be worthwhile across repeated queries. For AI pipelines, reducing redundant data scans can matter more than speeding up a single arithmetic operation. Measure the whole repeated workflow.

T(n)≈an+b,Tpairs(n)≈cn(n−1)2T(n)\approx a n+b,\qquad T_{\rm pairs}(n)\approx c\frac{n(n-1)}{2}
The first empirical model has a seconds-per-item coefficient a and fixed overhead b in seconds. In the pair model, c is seconds per pair. Both assume comparable item costs and stable operating conditions.↔ Scroll wide equations horizontally.

A benchmark answers a narrower question

Benchmark realistic sizes and distributions, record hardware and software versions, and separate startup from steady work when both matter. Report variability rather than a single conveniently low number. A dataset that fits in a cache may behave very differently once enlarged. Complexity predicts a possible growth trend; a benchmark estimates behavior under its documented conditions. Neither replaces the other, and neither proves correctness.

The lab fixes the growth shape to y=ax2y=ax^2: change coefficient aa and move position xx. At positive aa, doubling positive xx quadruples the modeled output. Interpret that as an all-pairs work illustration with normalized input size, not a timing benchmark. The controls cannot switch to a linear or logarithmic algorithm. Explain why this quadratic growth creates a capacity risk. Finally, ask whether a different data structure, batching approach, or problem formulation reduces the work before considering extra machines.

Avoid unnecessary pair comparisons

A deduplication prototype compares every unordered pair of 10,000 records. Each comparison takes an assumed constant two microseconds. What changes when the dataset doubles?

  1. For 10,000 records, count 10,000 × 9,999 / 2 = 49,995,000 unordered pairs. Self-comparisons and duplicate pair orders are excluded.

  2. Multiply by two microseconds per pair: the simplified compute estimate is 99.99 seconds. At 20,000 records there are 199,990,000 pairs, giving 399.98 seconds.

  3. Recognize almost fourfold growth. Consider an exact-key index if the definition of duplicate permits one, including its construction and memory costs; benchmark the replacement against the original correctness specification.

The result

Doubling this input roughly quadruples comparison time. The estimate assumes constant pair cost and excludes allocation, I/O, and scheduling.

Explore the model

Interactive lab

Interactive lab · function

Quadratic work under a microscope

For the fixed model y=ax², change coefficient a and move x. Compare the output at x and 2x when both are in range. This illustrates quadratic scaling; it does not time a search or change the algorithmic growth family.

Quadratic work under a microscopeThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA positive quadratic work model quadruples when positive input size doubles, even after its coefficient is reduced.

Check your understanding

An indexed method is faster for large inputs but slower for a single tiny query. Is that inconsistent with a better asymptotic bound?

Try it yourself

A linear scan averages 3 milliseconds for 20,000 items. Estimate time for 100,000 items if fixed overhead is negligible, then name one reason the estimate might fail.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Compare input sizes before multiplying the measured time.

Compare with the solution

The input is five times larger, giving approximately 15 milliseconds under a constant per-item-cost model. Cache misses, changed record sizes, I/O, or different target distributions can invalidate that assumption; benchmark at the larger size to check it.

Take it with you

  • Correctness depends on a clear input contract and maintained invariants.
  • Complexity predicts growth, not an exact latency.
  • Compare total workflow cost, including indexing and memory.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.