Trading Storage for Fewer Comparisons

A stored lookup can replace a repeated search when building and querying the lookup is cheaper for the workload.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two matching values
  2. Respect the position rule
  3. Check a complement before inserting the current value
  4. State the hash and output assumptions

Trace two matching values

To find a pair summing to ten, scan 3, 4, and 7. Record each seen value after checking for its complement. At seven the stored three gives a witness. The dictionary lookup supports that check.

Respect the position rule

For a target twice a value, check previous entries before inserting the current entry to avoid pairing an item with itself. Store needed index witnesses. The extra storage belongs in time and space accounting.[1]

Check a complement before inserting the current value

Find two positions summing to twelve in [9, 2, 10, 3]. At each value, look for the needed complement among earlier values. When the scan reaches ten, it finds the earlier two. Inserting before lookup requires extra care when one value is half of the target. See dictionary lookup.

Read 9: need 3, absent → store index 0
Read 2: need 10, absent → store index 1
Read 10: need 2, found at 1 → return (1,2)

State the hash and output assumptions

Expected constant-time map operations give a linear scan with linear auxiliary space. Reporting every matching pair can require quadratic output with repeats. Test a singleton of value six, then two sixes, to verify that a witness uses distinct positions.

References

  1. Jeff Erickson, Algorithms ↩