← All lessonsUnit 2 · One pass, remembering something
Lesson 2.8

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

Harper

I wrote a birthday checker. Does anyone at my party share a birthday? Ten guests: it answered at once.

Arthur

Congratulations.

Harper

Then I gave it the whole city.

Arthur

And?

Harper

I'll let you know. How do you tell how long code will take, before you run it?

Arthur

I don't time it. I count it. Put a clicker where the work happens, and click once each time.

Harper

One loop over ten guests?

Arthur

Ten clicks. Over a thousand guests, a thousand. The clicks grow with the guests.

Harper

And a loop inside a loop?

Arthur

For each guest, the inner loop meets every guest again. Ten guests, a hundred clicks. A thousand guests, a million clicks.

Harper

A hundred times the guests, ten thousand times the clicks.

Arthur

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.

Harper

Twenty for a million? That's nothing.

Arthur

That's the thing to hope for. Count first. Then ask how big the input can be.

Harper

The problem says the input can be a million.

Arthur

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.

Swift
/// 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.

Watch it run

Here are the counts. Each was counted by running the code, not worked out.

none loopa loop inside a loopevery pair oncehalvings
1010100454
10010010,0004,9507
1,0001,0001,000,000499,50010

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

Step 1

Count the steps of one loop for 10 things and for 1,000

Swift
/// 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.

Step 2

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:

Swift
/// 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.

Step 3

Count the steps when the range halves each time, for 1,000 and for 1,000,000

Swift
/// 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.

Step 4

Two loops one after the other, against one inside the other

Swift
/// 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:

Swift
/// 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).

Step 5

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.

Swift
/// 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.

Step 6

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:

Swift
/// 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.

Swift
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.

Step 7

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.

Swift
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

1

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.

2

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.

3

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.

4

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.

5

What extra memory does var seats = seats cost?

Show the answerHide the answer

O(n): a copy as long as the row.

6

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.

ProblemLevel
1Count the steps of one loopEasy
2Count a loop inside a loopEasy
3Count every pair onceEasy
4Count the halvingsEasy
5One after the other, or insideEasy
6Count both answersEasy
7Say how the steps growEasy
8Say the extra memoryEasy

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.