How the work grows
Before you write, count how the work grows with the input, and ask how big the input can be.
- Reach for it when
- Always, before you write: will this finish in time?
- The move
- Count the steps for n things. One loop is n. A loop inside a loop is n × n. Halving is about log n. Then ask how big n can be.
The idea
I wrote a birthday checker. Does anyone at my party share a birthday? Ten guests: it answered at once.
Congratulations.
Then I gave it the whole city.
And?
I'll let you know. How do you tell how long code will take, before you run it?
I don't time it. I count it. Put a clicker where the work happens, and click once each time.
One loop over ten guests?
Ten clicks. Over a thousand guests, a thousand. The clicks grow with the guests.
And a loop inside a loop?
For each guest, the inner loop meets every guest again. Ten guests, a hundred clicks. A thousand guests, a million clicks.
A hundred times the guests, ten thousand times the clicks.
That's the thing to fear. And there's a third kind. Cut the work in half each time, and a thousand takes ten clicks. A million takes twenty.
Twenty for a million? That's nothing.
That's the thing to hope for. Count first. Then ask how big the input can be.
The problem says the input can be a million.
Then a loop inside a loop is out before you've typed it.
That is the tool. Before you write, count the steps for n things, and see how they grow. One loop is n steps. A loop inside a loop is n × n. Cutting the work in half each time is about log n. Then read how big n can be, and you know whether an answer will finish.
The shape
This is what you know by heart: a counter where the work happens.
/// The steps a loop inside a loop takes over `n` things.
func stepsOfLoopInsideLoop(_ n: Int) -> Int {
var steps = 0
for _ in 0..<n {
for _ in 0..<n {
steps += 1 // the work happens here, so count it here
}
}
return steps
}It has three parts, and each is there for a reason.
- The counter.
stepsstarts at 0 and goes up by one each time the work is done. It counts what the code does, not how long the computer takes, so it gives the same number on every Mac and every run. - Where it goes.
steps += 1sits in the innermost place, where the work happens. Put it in the outer loop instead and you count the wrong thing. - The answer is a number for n. Run it for 10, then 100, then 1,000. What matters is not any one count but how the count grows from one to the next.
Watch it run
Here are the counts. Each was counted by running the code, not worked out.
| n | one loop | a loop inside a loop | every pair once | halvings |
|---|---|---|---|---|
| 10 | 10 | 100 | 45 | 4 |
| 100 | 100 | 10,000 | 4,950 | 7 |
| 1,000 | 1,000 | 1,000,000 | 499,500 | 10 |
Read each column downwards. From 100 to 1,000 the input grows ten times. One loop grows ten times too. A loop inside a loop grows a hundred times. Every pair once is about half of a loop inside a loop, and it grows a hundred times as well. Halvings grow by three. Those four kinds of growth are most of what this course needs.
Step by step
Count the steps of one loop for 10 things and for 1,000
/// The steps one loop over `n` things takes.
func stepsOfOneLoop(_ n: Int) -> Int {
var steps = 0
for _ in 0..<n {
steps += 1
}
return steps
}What is new: counting instead of timing. For 10 things the count is 10, and for 1,000 it is 1,000. Twice the input, twice the steps. This is called O(n), said "order n": the steps grow in step with the input.
Most of the tools so far are this. "Best so far", "Count as you go", "Running total", "Runs": each walks the array once and does a little at each element.
Count the steps of a loop inside a loop for 10 and for 1,000
This step is the shape itself.
What is new: the inner loop starts over for every pass of the outer one. So the outer loop's n passes each cost n steps, and the total is n × n: 100 for 10 and 1,000,000 for 1,000. Twice the input, four times the steps. This is O(n²), "order n squared".
The pairs from the last step of "Loops and indexes" are a loop inside a loop too. There the inner loop starts after the outer one, so each pair is met once:
/// The steps of a loop inside a loop whose inner loop starts after the outer one:
/// every pair `i < j`, once.
func pairSteps(_ n: Int) -> Int {
var steps = 0
for i in 0..<n {
for _ in (i + 1)..<n {
steps += 1
}
}
return steps
}That gives 45 for 10 and 499,500 for 1,000. It is about half of n × n, exactly n × (n − 1) / 2, and halving does not change the kind of growth. Ten times the input is still about a hundred times the steps. It is O(n²) as well.
Count the steps when the range halves each time, for 1,000 and for 1,000,000
/// How many times `n` can be halved, dropping the remainder, before nothing is left.
func halvings(_ n: Int) -> Int {
var size = n
var steps = 0
while size > 0 {
size /= 2 // half of what is left
steps += 1
}
return steps
}What is new: the work shrinks by half each time, instead of moving along by one. A thousand halves to nothing in 10 steps, and a million in 20. Doubling the input adds one step: 2,000 takes 11. This is O(log n), "order log n". It is the cost of the binary search in a later unit, and it is so small that it hardly matters how big the input is.
Two loops one after the other, against one inside the other
/// The steps of two loops over `n` things, one after the other.
func stepsOneAfterOther(_ n: Int) -> Int {
var steps = 0
for _ in 0..<n {
steps += 1
}
for _ in 0..<n {
steps += 1
}
return steps
}What is new: telling loops apart by how they sit. Two loops one after the other add their steps: 2,000 for 1,000. One inside the other multiplies them: 1,000,000. Twice n is still O(n): it grows in step with the input, only twice as fast.
So count the loops that sit inside each other, not the loops you can see. And look at whether the inner loop starts over. Here is the loop from "Runs" that jumps from run to run:
/// The steps of a loop inside a loop whose inner loop never goes back: it walks a run
/// of up to ten, and the outer loop jumps past it, as "Runs" does.
func stepsOfJumping(_ n: Int) -> Int {
var steps = 0
var start = 0
while start < n {
var end = start
while end < n && end < start + 10 {
end += 1
steps += 1
}
start = end // jump: this part is never walked again
}
return steps
}It is a loop inside a loop, and for 1,000 things it takes 1,000 steps. The inner loop never walks back over a part it has walked: the outer loop jumps past it. So every element is stepped over once, and the whole thing is O(n).
Which of two answers is faster for a million numbers?
Here is one question with two answers. Is any number in the array there twice? Each answer has a counter in it, passed in with inout so that the caller can read it.
/// Is any number there twice? The first way compares every pair.
func hasRepeatByPairs(_ numbers: [Int], steps: inout Int) -> Bool {
for i in numbers.indices {
for j in (i + 1)..<numbers.count {
steps += 1
if numbers[i] == numbers[j] {
return true
}
}
}
return false
}
/// The second way keeps a set of the numbers seen so far.
func hasRepeatBySet(_ numbers: [Int], steps: inout Int) -> Bool {
var seen: Set<Int> = []
for number in numbers {
steps += 1
if seen.contains(number) {
return true
}
seen.insert(number)
}
return false
}On 1,000 numbers with no repeats, the first answer compares 499,500 pairs and the second takes 1,000 steps. That is the whole decision. The first grows as n × n, and the second as n. For a million numbers the first compares 499,999,500,000 pairs, and the second takes a million steps.
What is new: reading an answer's growth off small counts, and trusting it for big ones. You do not have to run either answer on a million numbers to know which one to write.
To put a time on it: on the Mac that built this lesson, compiled as the app compiles your answers, a loop inside a loop over 3,000 numbers, 9,000,000 steps, took 0.51 seconds. One loop over the same numbers took less than a hundredth of a second. At that speed, the first answer on a million numbers would take about 8 hours.
Say a function's cost as O(n), O(n²) or O(log n)
From here on, every tool in the course says its cost in these words. To say them yourself, give each kind a name. Here they are as a Swift type:
/// How the work, or the memory, grows as the input grows.
enum Growth {
case one // O(1): the same, however large the input
case logN // O(log n): one more step each time the input doubles
case n // O(n): twice the input, twice the work
case nSquared // O(n²): twice the input, four times the work
}What is new: naming the growth without counting. Look at the loops: how they sit, and whether the work moves by one or shrinks by half.
func total(_ numbers: [Int]) -> Int { // one loop: .n
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func hasPairAddingTo(_ numbers: [Int], _ target: Int) -> Bool { // .nSquared
for i in numbers.indices {
for j in (i + 1)..<numbers.count {
if numbers[i] + numbers[j] == target {
return true
}
}
}
return false
}
func digitCount(_ number: Int) -> Int { // the number is cut by ten: .logN
var left = number
var digits = 1
while left >= 10 {
left /= 10
digits += 1
}
return digits
}total is one loop: .n. hasPairAddingTo is every pair once: .nSquared. digitCount cuts the number by ten each time, which is like halving with a bigger cut, so each extra digit costs one more step: .logN. When you are not sure, count it for 10 and 1,000 and see which column of the table it matches.
Say what extra memory it uses
Memory grows too. Here the question is what the function makes besides its input: a few variables, or something as long as the input.
func largest(_ numbers: [Int]) -> Int { // two variables, whatever the size: .one
var best = numbers[0]
for number in numbers {
best = max(best, number)
}
return best
}
func runningTotals(_ numbers: [Int]) -> [Int] { // a new array as long as the input: .n
var totals: [Int] = []
var sum = 0
for number in numbers {
sum += number
totals.append(sum)
}
return totals
}What is new: counting space instead of steps. largest keeps one variable however long the array is: its extra memory is .one, O(1). runningTotals builds a new array with one entry for every number: .n, O(n). The input itself does not count. It was there before the function started.
A copy counts. var seats = seats in "Take it as soon as you can" made a copy of the row, so that function used O(n) extra memory, and that was the price of marking.
What goes wrong
Counting the loops you can see. Two loops one after the other are O(n). A loop inside a loop whose inner loop never goes back, as in "Runs", is O(n) too. It is how the loops sit, and whether the inner one starts over, that counts.
Missing a hidden loop. Some lines are loops in disguise. contains on an array walks the array, so contains inside a loop is a loop inside a loop. count on a String walks the string, as "A string as an array of characters" showed. sorted() does more than one pass. On a Set, contains is one step, which is why the second answer in step 5 uses one.
Trusting small inputs. On ten guests the birthday checker answered at once, and so would anything. The table shows the difference only as n grows. Read the problem's limit on n before you choose.
Taking a constant for growth. Twice n is still O(n), and half of n × n is still O(n²). The kind of growth decides which answer finishes. The constant in front only matters between two answers of the same kind.
Forgetting memory. A copy of the input, or a new array as long as it, is O(n) memory. That is usually fine. Notice it anyway, because some problems say "use only a few variables".
Say it back
Why count steps instead of timing the code?
Show the answerHide the answer
A count is the same on every Mac and every run, and it shows how the work grows. A time depends on the machine and on what else it is doing.
How do the steps grow for one loop, a loop inside a loop, and halving, when the input is ten times bigger?
Show the answerHide the answer
One loop: ten times. A loop inside a loop: a hundred times. Halving: a few more steps, three or four.
Two loops, one after the other, over the same n things. What is the cost?
Show the answerHide the answer
O(n). The steps add up to 2 × n, and that still grows in step with the input.
The inner loop of "Runs" sits inside the outer one. Why is the whole thing O(n)?
Show the answerHide the answer
The inner loop never walks back over what it has walked, and the outer loop jumps past it. So each element is stepped over once.
What extra memory does var seats = seats cost?
Show the answerHide the answer
O(n): a copy as long as the row.
Why is Harper's birthday checker still running?
Show the answerHide the answer
It compares every pair of guests: a loop inside a loop. Ten guests make 45 pairs. A city of a million makes 499,999,500,000. At the speed this lesson measured, that is about 8 hours. A set of the birthdays seen so far would answer in one pass: a million steps.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Count the steps of one loop | Easy |
| 2 | Count a loop inside a loop | Easy |
| 3 | Count every pair once | Easy |
| 4 | Count the halvings | Easy |
| 5 | One after the other, or inside | Easy |
| 6 | Count both answers | Easy |
| 7 | Say how the steps grow | Easy |
| 8 | Say the extra memory | Easy |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.