Lesson 115 of 296
Big-O: time complexity
What you will learn
- Why we measure algorithms by how they grow
- What Big-O notation means
- The common complexities, from fastest to slowest
- How to work out the Big-O of your own code
- The rules for simplifying Big-O
On this page
Why measure growth?
Two solutions can both give the right answer. One finishes in a millisecond for a million items; the other takes hours. Timing code on your laptop is not reliable (computers differ, inputs differ). Instead we ask:
"As the input gets bigger, how does the number of steps grow?"
The size of the input is called n: the number of items in an array, characters in a string, nodes in a tree.
Big-O notation
Big-O describes how the running time grows as n grows, usually in the worst case. It ignores small details and focuses on the shape of the growth.
| Big-O | Name | Example | Steps when n = 1,000 |
|---|---|---|---|
| O(1) | Constant | Read arr[5], map.get(key) | 1 |
| O(log n) | Logarithmic | Binary search | about 10 |
| O(n) | Linear | One loop over the array | 1,000 |
| O(n log n) | Linearithmic | Good sorting algorithms | about 10,000 |
| O(n²) | Quadratic | A loop inside a loop over the same array | 1,000,000 |
| O(2ⁿ) | Exponential | Trying every subset | more than the atoms in the universe |
| O(n!) | Factorial | Trying every ordering | even more |
(O(n²) is said "O of n squared". O(2ⁿ) is "O of 2 to the n".)
What each one means in plain words
- O(1): the same time however big the input. Looking up by index or by key.
- O(log n): each step halves the problem. Doubling the input adds only one step. log₂ of 1,000,000 is about 20.
- O(n): look at each item once.
- O(n log n): sorting. Slightly more than linear.
- O(n²): compare every item with every other item.
- O(2ⁿ): every item is either in or out, and you try all combinations.
Working out the Big-O of code
One loop: O(n)
function sumAll(nums: number[]): number {
let total = 0;
for (const n of nums) total += n;
return total;
}A loop inside a loop: O(n²)
function hasDuplicateSlow(nums: number[]): boolean {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] === nums[j]) return true;
}
}
return false;
}The inner loop runs about n times for each of the n outer turns: about n × n / 2 steps, which is O(n²).
Two loops one after another: O(n + n) = O(n)
function minAndMax(nums: number[]): [number, number] {
let min = Infinity;
let max = -Infinity;
for (const n of nums) min = Math.min(min, n);
for (const n of nums) max = Math.max(max, n);
return [min, max];
}Halving each time: O(log n)
function countHalvings(n: number): number {
let steps = 0;
while (n > 1) {
n = Math.floor(n / 2);
steps++;
}
return steps;
}The simplification rules
- Drop constants. O(2n) is O(n). O(500) is O(1). We care about the shape, not the exact count.
- Keep only the biggest term. O(n² + n) is O(n²), because n² dominates as n grows.
- Different inputs get different letters. Looping over array
athen arraybis O(a + b), not O(n). A loop overainside a loop overbis O(a × b).
Hidden costs in JavaScript
Some built-in methods are loops themselves:
| Operation | Cost |
|---|---|
arr[i], arr.push, arr.pop | O(1) |
arr.shift, arr.unshift | O(n): every item moves |
arr.includes, indexOf, find | O(n) |
arr.slice, [...arr], concat | O(n): copies |
arr.sort | O(n log n) |
map.get, map.set, set.has | O(1) on average |
str + str in a loop | Can be O(n) per join; prefer an array and join (Lesson 120) |
Object.keys(obj) | O(number of keys) |
So this looks like one loop but is O(n²):
function uniqueSlow(nums: number[]): number[] {
const result: number[] = [];
for (const n of nums) {
if (!result.includes(n)) result.push(n);
}
return result;
}includes loops over result every time. Replacing the array with a Set makes it O(n) (Lesson 122).
What is fast enough?
A rough guide for coding tests, where about 10 to 100 million simple steps take around a second:
| Input size n | Usually acceptable |
|---|---|
| up to about 10 to 20 | O(2ⁿ), O(n!) |
| up to about 500 | O(n³) |
| up to about 5,000 to 10,000 | O(n²) |
| up to about 1,000,000 | O(n log n) or O(n) |
| larger | O(log n) or O(1) |
The constraints in a problem ("1 ≤ n ≤ 100,000") are a hint about the expected complexity.
How to say it in an interview
"Big-O describes how running time grows with input size in the worst case, ignoring constants and lower-order terms. A single loop is O(n), nested loops over the same input are O(n squared), halving the problem each step is O(log n), and good sorts are O(n log n). I watch for hidden loops like includes, shift or slice inside a loop, and I use the input constraints to judge what complexity is needed."
Key words
| Word | Meaning |
|---|---|
| Algorithm | A step-by-step method to solve a problem |
| Time complexity | How the number of steps grows with input size |
| Big-O | Notation for the upper bound of that growth |
| n | The size of the input |
| Constant / linear / quadratic | O(1) / O(n) / O(n²) |
| Logarithmic | O(log n): halving the problem each step |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.