Big-O Notation
How Big-O describes the way running time and memory grow with input size, how to read it from code, and what interviewers ask about it.
On this page
Big-O notation describes how the running time or memory use of an algorithm grows as its input gets larger. It is used to compare two solutions to the same problem without running them, and to decide whether a solution will be fast enough for the largest input the problem allows. You reach for it whenever you choose between approaches, and in an interview you are expected to state it for every solution you write.
Without it, you can only measure how long code takes on the inputs you happen to test. A duplicate check that compares every name with every other name finishes instantly on 100 names and takes minutes on a million, and nothing in the small test shows that.
How Big-O is counted
Big-O counts basic steps, such as comparisons, additions and lookups, instead of seconds. A stopwatch measures one machine on one input, while a step count depends only on the algorithm. You then ask how that count changes as the input size, written n, grows.
The slow duplicate check below compares each name with every name after it and stops at the first match. The trace counts the comparisons.
for i from 0 to n - 1: for j from i + 1 to n - 1: if names[i] == names[j]: return truereturn false- names0Anai1Benj2Cat3Ben
- comparisons
- 1
1The pointer
iis on Ana andjis on Ben. The names are different, so this is comparison 1. - names0Anai1Ben2Catj3Ben
- comparisons
- 2
2Ana and Cat are different, so this is comparison 2.
- names0Anai1Ben2Cat3Benj
- comparisons
- 3
3Ana and the last Ben are different, so this is comparison 3, and Ana has now been checked against every later name.
- names0Ana1Beni2Catj3Ben
- comparisons
- 4
4The pointer
imoves to Ben. Ben and Cat are different, so this is comparison 4. - names0Ana1Beni2Cat3Benj
- comparisons
- 5
5Ben and Ben match, so the function returns true after 5 comparisons.
- names0Ana1Ben2Cat3Ben
- n
- 4
- worst case
- 6
- n = 1,000
- 499,500
6If no name had matched, 4 names would have cost 3 + 2 + 1 = 6 comparisons. For
nnames the worst case is n(n − 1) / 2 comparisons, which is 499,500 for 1,000 names.
The exact count is more detail than you need. What matters is that doubling the number of names roughly quadruples the comparisons, and Big-O is a way of writing that down.
Dropping constants and smaller terms
To turn a step count into Big-O, remove constant factors and keep only the term that grows fastest. The count n(n − 1) / 2 expands to n²/2 − n/2. For large n the n/2 part is negligible next to n²/2, and the division by 2 does not change how the count grows, because doubling n still quadruples it. The result is O(n²), read as "order n squared".
3n + 5becomes O(n).n² + 100nbecomes O(n²).7becomes O(1), because the work does not depend onnat all.
Common growth rates
A small set of growth rates covers almost every algorithm in this course.
O(1), constant. The work does not change with the input size. Reading arr[i] and looking up a key in a hash map are O(1).
O(log n), logarithmic. Each step throws away a fixed fraction of the remaining input, usually half. You can halve n only about log₂(n) times before one item is left, so a million items need about 20 steps. The base of the logarithm is not written in O(log n), because changing the base only multiplies the count by a constant, which Big-O drops. Binary search is the standard example.
O(n), linear. The work is proportional to the input, as in one pass over a list.
O(n log n), linearithmic. This is a pass over the input repeated for each of about log n levels. Efficient sorting algorithms, such as merge sort, have this cost, and it is the usual cost of "sort first, then scan".
O(n²), quadratic. The work grows with every pair of items, which is what a loop nested inside a loop over the same input produces.
There are also exponential rates such as O(2ⁿ), where each extra item doubles the work. They appear in brute-force solutions that try every subset or every branch of a naive recursion, and they are only usable for inputs of roughly 20 to 25 items.
| Big-O | Name | n = 1,000 | n = 1,000,000 | Typical example |
|---|---|---|---|---|
| O(1) | constant | 1 | 1 | read arr[i], hash map lookup |
| O(log n) | logarithmic | 10 | 20 | binary search |
| O(n) | linear | 1,000 | 1,000,000 | one pass over a list |
| O(n log n) | linearithmic | 10,000 | 20,000,000 | efficient sorting |
| O(n²) | quadratic | 1,000,000 | 1,000,000,000,000 | comparing every pair |
Reading Big-O from code
Three rules are enough for most code you will write:
- Steps in sequence add, and the largest term wins. A loop over
nitems followed by another loop overnitems costs 2n steps, which is O(n). - Nested loops multiply. A loop over
nitems inside a loop overnitems is O(n²). - Halving the input at each step gives O(log n).
The faster duplicate check stores each name in a set as it goes. Asking whether a name is already in the set takes one step on average, so the inner loop disappears.
// O(n²) time: compare every pair
function hasDuplicateSlow(names) {
for (let i = 0; i < names.length; i++) {
for (let j = i + 1; j < names.length; j++) {
if (names[i] === names[j]) return true;
}
}
return false;
}
// O(n) time: remember what you have seen
function hasDuplicate(names) {
const seen = new Set();
for (const name of names) {
if (seen.has(name)) return true; // O(1) on average
seen.add(name);
}
return false;
}# O(n²) time: compare every pair
def has_duplicate_slow(names):
for i in range(len(names)):
for j in range(i + 1, len(names)):
if names[i] == names[j]:
return True
return False
# O(n) time: remember what you have seen
def has_duplicate(names):
seen = set()
for name in names:
if name in seen: # O(1) on average
return True
seen.add(name)
return FalseSpace complexity
Big-O also measures memory. The faster version stores up to n names in the set, so it uses O(n) extra space, while the slower version only keeps two index variables, which is O(1). Extra space means memory the algorithm allocates beyond the input itself.
Trading memory for time like this is the most common trade in algorithm problems. It is usually the right choice, unless the data is too large to hold a second copy of in memory.
| Approach | Time | Space | Why |
|---|---|---|---|
| Compare every pair | O(n²) | O(1) | It uses nested loops and stores nothing. |
| Set of seen names | O(n) | O(n) | It makes one pass, but the set can hold every name. |
Worst case, amortized cost and other ways to state complexity
Worst, average and best case
If the first two names are the same, even the slow duplicate check stops after one comparison. That is its best case. Big-O is normally quoted for the worst case, because that is the input that causes timeouts, and you should assume the worst case whenever nobody says otherwise. When a cost is stated for the average case, it should be labelled as such, as with hash set lookups, which are O(1) on average and O(n) in the worst case if many keys collide.
Amortized cost
Some operations are usually cheap and occasionally expensive. Appending to a dynamic array, such as a JavaScript array or a Python list, normally writes one element, but when the array is full it allocates a larger one and copies every element. The expensive copy happens rarely enough that the average cost over a long run of appends is constant, so appending is described as O(1) amortized. A single append can still take O(n).
More than one input
When a function takes two independent inputs, the cost uses two variables. Comparing every element of an array of n items with every element of an array of m items is O(n × m), and scanning one array and then the other is O(n + m). Writing both as n is wrong, because the two sizes can differ by a large factor.
Big-O, Big-Omega and Big-Theta
Strictly, O(f(n)) is an upper bound: the running time grows no faster than f(n). Big-Omega, written Ω, is the matching lower bound, and Big-Theta, written Θ, means the running time is bounded both above and below by the same growth rate. In everyday use and in interviews, people say "O(n)" when they mean the tightest bound they can prove, so state the tightest one. Saying a linear scan is O(n²) is technically true but not useful.
When Big-O does not decide
Big-O ignores constant factors, so it only tells you which algorithm wins for large inputs. For small inputs a simple O(n²) method can beat a more complex O(n log n) one. Two algorithms with the same Big-O can also differ by a factor of ten in practice, for example because one of them uses memory in a cache-friendly way. Use Big-O to rule out solutions that are far too slow, and do not use it to rank two solutions that are close.
Pitfalls when counting complexity
In the interview
You are expected to give the time and space complexity of every solution without being asked, and to say which input each variable stands for. The problem statement tells you the target. Look for the constraints: if n can be 100,000 and your approach is O(n²), that is 10 billion steps, which is too slow, while O(n log n) is about 1.7 million steps, which is fine. As a rough planning figure, aim for no more than 100 million simple operations in total.
These are the questions interviewers usually ask next, with answers you can adapt.
What is the time and space complexity of your solution?
Give both, name the variables, and say which case you mean. For example: "This is O(n) time and O(n) space, where n is the number of names. The set can hold every name in the worst case." Interviewers notice when candidates forget the space cost, especially when a hash map is involved.
Can you do better?
This usually means the interviewer knows a faster approach, and the answer is almost always to trade memory for time or to use the structure of the input. Look at which operation repeats inside the loop, such as a lookup or a search, and ask whether a hash map or a sorted order makes it O(1) or O(log n). If you do not see an improvement, say what the bottleneck is and why you think it is hard to remove.
A hash map lookup is O(1), so why do some people say O(n)?
The O(1) figure is the average case. If many keys land in the same bucket, a lookup has to compare against all of them, so the worst case is O(n). With a good hash function this is very rare, and in an interview you can say "O(1) on average" and leave it there.
Is this the worst case or the average case?
Answer with the worst case unless you are asked about the average, and name any input that triggers it. For the duplicate check, the worst case is a list with no duplicates, which forces the full n(n − 1) / 2 comparisons.
What is the space complexity of a recursive solution?
Count the maximum depth of the recursion, because each active call holds a stack frame. A recursive binary search is O(log n) space for that reason, and an iterative one is O(1). A depth-first search of a tree with h levels uses O(h) space.
Why is appending to a list O(1) if it sometimes copies everything?
The cost is amortized. The array grows by a constant factor, for example doubling, so copying happens after 1, 2, 4, 8 and so on appends. Over n appends the total copying is less than 2n element writes, which averages to a constant cost per append.
Why do we write O(log n) without a base?
Logarithms of different bases differ only by a constant factor, because log₂(n) = log₁₀(n) / log₁₀(2). Big-O drops constant factors, so the base does not matter and is left out.
What is the difference between O and Θ?
O is an upper bound and Θ is a tight bound. If an algorithm always takes about n steps, it is Θ(n) and also O(n) and O(n²), but you should quote the tightest bound. Most interviewers accept O(n) as the answer in that case.
A function loops over a list of n items. Inside the loop, it calls items.includes(x) on the same list. What is its time complexity?
Which of these step counts simplifies to O(n)?
Code A takes 2n steps and code B takes n² / 100 steps. Which does fewer steps when n = 10?
What to practise next
The faster duplicate check depends on a hash set answering "is this value already stored?" in one step, which is covered in Hash Tables. To apply it right away, solve Matching Receipts, where the obvious solution is O(n²) and a map brings it down to O(n).