Big O notation explained
Move the slider to change the input size n, and tick the growth rates to compare. The table shows how many steps each one needs and how long that takes on a computer doing a billion simple steps per second. Turn on the log scale to fit them all on one graph.
What Big O measures
Big O notation describes how the number of steps an algorithm needs grows as the input gets bigger. It ignores the speed of the computer and small details, and keeps only the part that matters for big inputs. If an algorithm takes 3n² + 5n + 2 steps, it is O(n²): for large n, the n² part swamps everything else.
The common classes
- O(1): the same time however big the input, like reading one array element.
- O(log n): each step halves the problem, like binary search.
- O(n): look at each item once.
- O(n log n): the fastest general-purpose sorting.
- O(n²): compare every pair, as in a loop inside a loop.
- O(2ⁿ) and O(n!): try every combination or every order. Fine for n = 10, impossible for n = 100.
Reading code
A single loop over n items is O(n). A loop inside a loop is O(n²). A loop that halves its range each time is O(log n). Steps one after another add, and the biggest term wins: an O(n) step followed by an O(n²) step is O(n²) overall.
Best, average and worst case
The same algorithm can behave differently on different inputs. Insertion sort is O(n) on a list that is already sorted, but O(n²) on a reversed one. Big O usually describes the worst case, so you know the most it could ever take. Space (memory) is measured the same way.
Questions students ask
What does O(n) mean?
O(n) means the number of steps grows in proportion to the size of the input: doubling the input roughly doubles the time, as when you check every item in a list once.
Why is O(log n) so fast?
O(log n) is fast because each step halves the remaining problem, so even a billion items need only about 30 steps.
Is O(n log n) better than O(n²)?
Yes. For large inputs O(n log n) is far better than O(n²): sorting a million items takes about 20 million steps with an O(n log n) algorithm but about a trillion with an O(n²) one.
Check yourself
3 quick questions. Tap an answer to see if you are right.
1. An algorithm with two nested loops over n items is usually…
n iterations of an inner loop that runs n times: n × n.
2. Which grows slowest?
log n grows very slowly: about 30 for a billion items.
3. 3n² + 5n + 7 is…
Keep only the fastest-growing term and drop constant factors.
Related
More computer science
Connected tools
The same idea from another angle, across the site.