Unit 5 · Data and algorithms
What O(1) really means
O(1), constant time, means the work does not grow with the size of the data. It might be one step or fifty, but it is the same fifty for 3 items or 3 million.
The mix-up
What people often think
“O(1) means the code takes exactly one step.”
What the tutor says
O(1) means the work stays the same no matter how much data there is. It could be one step or fifty, but it never grows.
How it works
Looking up a key in an object is the classic example: contact.phone takes the same time with 3 keys or 3,000, because the object jumps straight to the key instead of scanning.
Short code is not the same as fast code. A single line like list.includes(x) still visits every item, so its work grows with n.
Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Finding a key means searching through the whole object.”
Objects jump straight to a key. contact.phone takes the same time with 3 keys or 3,000.
“One short line of code is O(1).”
Length of code is not the point. A one-line loop still visits every item, so its work grows with n.
Practise it with a tutor watching
Big O by feel
Look at a piece of code and say roughly how its work grows as the data grows.
Free with an account. The first two units need no account.