Computer Science I / Hashing and Dictionaries
Practice question · Multiple choice

Hash-table lookup is described as O(1), yet the worst case is O(n). Why is the constant-time figure still the honest way to describe it?

Hints
  1. Ask what has to be true for all n keys to end up in one bucket.
  2. Is the O(1) an average or a guarantee? Which one is being claimed?
Show the answer

A. Because O(1) is the expected cost under a hash that spreads keys evenly.

Why

The O(1) is an expected cost: with a decent hash and a bounded load factor each bucket holds a small constant number of entries. The worst case is improbable by accident and reachable on purpose, an attacker who knows the hash function can construct colliding keys and turn every lookup linear. The defence is per-process randomised hashing, which most runtimes now do.

Read the lesson: Hashing and Dictionaries →

Practise Hashing and Dictionaries

The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Hashing and Dictionaries