Early Returns and Worst-Case Running Time

An early return can reduce work for some inputs without changing the worst-case growth rate.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Examine a successful input
  2. Generalize the witness
  3. Build a workload that reaches the final guard
  4. Count the cost of each check as well

Examine a successful input

Searching 4, 8, 9 for 4 uses one equality check. An absent target uses all three. Two examples at the same length establish different costs from one first-match scan.

Generalize the witness

For every length, an input with no matching value forces the scan through the full sequence. An early success does not remove that family of calls. To argue about typical cost, state the input distribution rather than extrapolate from a fast test.[1]

Build a workload that reaches the final guard

A record validator stops on the first invalid row. For a batch of six rows, one bad record in position zero yields one validation. A batch whose only bad row is last, or which is entirely valid, triggers all six. See first-match scans.

First bad at index 0: 1 row check
First bad at index 5: 6 row checks
No bad row: 6 row checks
Empty input: 0 row checks

Count the cost of each check as well

If each row check parses a text field, a six-row batch can vary greatly in byte size. A true bound may depend on the sum of lengths of the inspected fields. Use records with comparable per-row work when comparing early and late outcomes.

References

  1. Jeff Erickson, Algorithms ↩