MEPX
Chapter 7 of 12All chapters

Chapter 7 of 12

Best, average and worst

One algorithm, three answers.

Which one to quote

Best case is usually useless, average describes normal behaviour, and worst case is what you promise. Quote the average when describing typical performance and the worst when it matters for safety.

  • Quicksort: O(n log n) average, O(n squared) worst.
  • Hash map lookup: O(1) average, O(n) worst.

Adversarial input

A worst case that never happens by accident can be provoked on purpose. Attacks that force hash collisions turn a fast lookup into a linear scan, which is why libraries randomise their hashes.