Module 2 · Measuring Speed and Memory · Lesson 3 of 40
Big-O: how work grows
Count steps instead of seconds, and describe how the steps grow as the input gets bigger.
In this lesson · about 20 minutes
- Explain what n means
- Read O(1), O(n) and O(n²) in plain words
- Count the steps of a simple loop
How fast is a program? Seconds are a bad measure: a new laptop is faster than an old phone. Instead we ask a better question:
"When the input gets bigger, how fast does the number of steps grow?"
This is called time complexity.
What is n?
We use the letter n for the size of the input. For a list, n is the number of items. For a word, n is the number of letters. If there are two different inputs, we use two letters, like n and m.
Big-O
We write the growth with Big-O. Read O(n) as "order n". It describes the worst case, the most work the code could need. Here are the most common ones, from fastest to slowest:
| Big-O | Name | Plain words | Example |
|---|---|---|---|
| O(1) | constant | Same work, any size | Read nums[5] |
| O(log n) | logarithmic | Cut the problem in half each step | Binary search |
| O(n) | linear | Look at each item once | Find the biggest number |
| O(n log n) | n log n | A bit more than linear | Good sorting (merge sort) |
| O(n²) | quadratic | Compare every item with every item | Two loops, one inside the other |
| O(2ⁿ) | exponential | Doubles with every extra item | Trying every subset |
Try it · see it work
How fast does the work grow?
Pick a size for n. Watch how quickly O(n²) and O(2ⁿ) get out of hand.
Times assume a computer that does about one billion simple steps a second. Bars use a squeezed (log) scale so they all fit; the real gaps are far bigger. Try n = 1,000,000 and look at O(n²).
Counting steps
Let's count. This loop prints every item once:
for x in nums:
print(x)
If nums has n items, the loop runs n times. So it is O(n).
This code has a loop inside a loop:
for a in nums:
for b in nums:
print(a, b)
For each of the n values of a, the inner loop runs n times. That is n × n = n² steps, so it is O(n²).
And this line does one step no matter how long the list is:
first = nums[0]
That is O(1).
Try it: count the steps yourself
Run it, then change n to 20 and 40. Watch how the two counts grow differently.
Exercise
Count the pairs
Write count_steps(n) that returns how many times the inner line runs in this code, by actually running loops and counting:
for i in range(n):
for j in range(n):
... # this lineCheck your understanding0 of 4 correct
Quiz score: 0 of 4
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.