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
The question for today
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.
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.
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 : change coefficient and move position . At positive , doubling positive 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.
Work it through
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?
For 10,000 records, count 10,000 × 9,999 / 2 = 49,995,000 unordered pairs. Self-comparisons and duplicate pair orders are excluded.
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.
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.
Doubling this input roughly quadruples comparison time. The estimate assumes constant pair cost and excludes allocation, I/O, and scheduling.
The living notebook
Explore the model
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.
- y at chosen x
- 0.608
- Tangent slope · 2ax
- 1.35
- Signed area · ax³/3
- 0.182
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.
Pause & reason
Check your understanding
Your turn
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.
Keep the idea
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.