The Plain Picture#
Searching for your keys in a row of 10 drawers. Best case: first drawer. Worst case: last drawer (or not there at all). Average: somewhere in the middle. "How long does it take?" depends on which case you mean.
The Real Names#
Worst case — the maximum steps over all inputs of size n. This is what interviewers mean by default. It's a guarantee.
Best case — the minimum. Rarely useful ("linear search is O(1) if the item is first" tells you nothing).
Average case — the expected steps over typical/random inputs. Important for hash tables and quicksort.
Three notations:
O (Big-O) — upper bound: grows no faster than.
Ω (Big-Omega) — lower bound: grows at least as fast as.
Θ (Big-Theta) — tight bound: both — grows exactly like (up to constants).
Engineers usually say "O" when they mean a tight bound ("this loop is O(n)"). That's fine in interviews; just know the difference exists.
Under the Hood — examples that matter#
| Operation | Best | Average | Worst | Why the worst case happens |
|---|---|---|---|---|
| linear search | O(1) | O(n) | O(n) | item at the end or missing |
HashMap.get | O(1) | O(1) | O(log n) in Java 8+ (O(n) in older Java) | many keys in the same bucket (Collections, From the Inside) |
| quicksort | O(n log n) | O(n log n) | O(n²) | always picking a bad pivot (Sorting (coming soon)) |
| insertion sort | O(n) (already sorted) | O(n²) | O(n²) | reverse-sorted input |
When you state a complexity in an interview, say which case: "O(n) on average, because hash-set insertion is expected constant time."
Check yourself
3 questionsWhich case do interviewers mean by default?
Show answerHide answer
The worst case.
What's the difference between O, Ω and Θ?
Show answerHide answer
Upper bound, lower bound, tight (both) bound.
Why do we usually quote HashMap operations as O(1) even though the worst case is worse?
Show answerHide answer
With a good hash function the expected (average) cost is constant, and the worst case is rare in practice.