iq.lab
Python starts when a code cell comes near or you run one
02 Counting steps: Big O

Lesson 1 of 3

Counting steps

Before you can say what a solution costs, you count how many times its loop body runs. One loop over n items runs n times, two nested loops over the same items run n × n times, and a loop that halves what is left runs only 29 times on a billion items.

About 1 hour 5 minutes
By the end you can
  • Count how many times a loop body runs, for one loop, two nested loops and a loop that halves

  • Explain why we count passes of the loop body instead of every line

  • Say how each count changes when the input doubles

  • Tell the best case from the worst case for a search that can stop early

  • State the worst-case cost of a loop out loud, the way an interviewer expects

Your nightly job checks a table of orders for repeated ids by comparing every order with every other order. On 1,000 orders it takes 1 second. Next quarter the table holds 100,000 orders. How long will the job take?

It is not 100 seconds. The table grew 100 times, but the number of comparisons grew about 10,000 times. If the time follows the comparisons, the job now takes about 10,000 seconds, close to three hours. By the end of this lesson you will see that from the code alone, in a few seconds, by counting how many times the loop body runs.

Every algorithm in this course is a walk over the data, a notebook of notes, a promise about what the notes mean, and a cost. This module is about the cost. Interviewers expect you to state it for every solution without being asked, and the answer always starts with the same move: count the steps on a small input, then say how the count grows.

What counts as a step

Before we count, we need to agree on what we are counting.

A step is one simple operation: add two numbers, compare two values, read one item of a list, point a name at a value. Each one takes about the same short time, whatever the size of the input. A computer does millions of them per second, so one step is never the problem. The problem is how many there are.

Counting every operation exactly is fussy, and it does not change what we care about: how the count grows. Instead we count how many times the loop body runs. The loop body is the indented lines under a for or while, and one run of it is one pass. Each pass does a fixed handful of steps, so if the body runs 10 times, the work is 10 handfuls. (That holds while every line in the body is a simple step. A line such as x in nums hides a walk over the whole list; the last lesson of this module prices those lines.) In this module, n stands for the size of the input: the number of items in the list.

To make the count visible, we add one extra name, steps, and add 1 to it on every pass. steps is our tally of passes, not part of the answer. (steps += 1 is shorthand for steps = steps + 1.) Do not mix it up with the viewer's "Step k of N" counter, which moves once per line run: the tally moves once per pass of the body. Here is the running total from module 1 with a tally added. Before you step through, guess what steps ends as.

Step throughTallying the passes of one loop
Step 1 of 18
Line 1 is about to run.
orders = [12, 30, 7, 25]
total = 0
steps = 0
for x in orders:
total += x
steps += 1
print(total, steps)
Names
no names yet
Output
(nothing printed yet)

The tally ends at 4 because the list has 4 items. Give the loop 10 items and it ends at 10; give it a million and it ends at a million. One loop over n items runs its body n times.

What about the lines outside the loop? total = 0, steps = 0 and the print run once each, however long the list is. Lines outside the loop are a fixed cost; the loop body is the part that grows. That is why we count the body. (The for line is highlighted 5 times in the trace: once per item, plus one last time to find the list used up. That one extra check does not grow with n either.)

People write "the work grows in step with n" as O(n), read "order n". You met that label in module 0 and in module 1's frame cards. The next lesson explains exactly what the O keeps and what it drops. This lesson is about the count underneath it.

Now count a loop that has an if inside its body.

PredictA tally with an if inside

Type exactly what this prints. range(2, 7) starts at 2 and stops before 7, and i % 2 == 0 is true when i is even.

steps = 0
hits = 0
for i in range(2, 7):
    steps += 1
    if i % 2 == 0:
        hits += 1
print(steps, hits)

Two loops, one inside the other

What happens when the body of a loop is itself a loop?

Back to the opening job. The plainest way to find a repeated value is to compare every position with every other position. That takes two loops, one inside the other (a nested loop): the outer loop picks a position i, and for each i, the inner loop walks a second position j across the whole list. Module 0 started j one place right of i; this plainer version lets j visit every position, i included, so it needs the check i != j (!= means "is not equal to"). The arrows under the list show i and j. Before you step through, guess: on a list of 3 numbers with no repeat, how many times does steps += 1 run?

Step throughComparing every pair of positions
Step 1 of 39
Line 1 is about to run.
def has_duplicate(nums):
steps = 0
for i in range(len(nums)):
for j in range(len(nums)):
steps += 1
if i != j and nums[i] == nums[j]:
return True
return False
Names
no names yet
Output
(nothing printed yet)

For each of the n values of i, the inner loop runs n times, so the body runs n × n times. That is written n2 ("n squared") and labelled O(n2). Here is what it does as the list grows:

Items (n)Passes of the inner body (n × n)
39
10100
1,0001,000,000
100,00010,000,000,000

This is the opening job. Going from 1,000 to 100,000 orders is 100 times more items, and n × n turns 100 times more items into 10,000 times more work.

Two loops do not always mean n × n. Count what each loop walks, then multiply.

Quick checkIs every nested loop n × n?

nums has n items. How many times does steps += 1 run?

steps = 0
for x in nums:
    for k in range(3):
        steps += 1

Choose one answer, then check.

Each pair once

The trace did wasted work. It compared position 0 with position 1, and later position 1 with position 0. It also visited i == j, which needed the i != j guard. Start the inner loop at i + 1, as module 0 did, and each pair is compared exactly once. range(i + 1, len(nums)) gives the positions after i, so j never equals i and never goes back.

Before you run this, count by hand how many times steps += 1 runs on these 4 items. Then run it to check.

⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

Here is the count, one row per value of i. Each row has one fewer pass than the row before:

ij takesPasses
01, 2, 33
12, 32
231
3nothing0
total6

In general the count is (n − 1) + (n − 2) + ... + 1 + 0, which adds up to n(n − 1)/2. For n = 4 that is 4 × 3 / 2 = 6, matching the table and the 6 the code prints.

Why n(n − 1)/2: the full loop met every pair twice. You can see it in the trace above. Of its 9 passes, 3 had i == j. The other 6 were the 3 pairs of positions, each met twice: positions 0 and 1, for example, came up as i = 0, j = 1 and again as i = 1, j = 0. In general, n × n passes minus the n with i == j leaves n(n − 1), and each pair appears twice in that, so the pairs number n(n − 1)/2.

Half the work is still the same shape. At n = 1,000 it is 499,500 comparisons instead of 1,000,000, and doubling n still multiplies the count by about 4. That is why both versions get the same label, O(n2); the next lesson makes this precise.

Work it outEach pair once

What is steps after this code runs? Type a whole number.

steps = 0
for i in range(5):
    for j in range(i + 1, 5):
        steps += 1
steps

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Here is the every-pair check with the inner loop starting at i + 1, described by the four answers (walk, notebook, promise, cost). You will build its code in the puzzle after the card. O(1) extra space means the extra memory is a fixed handful of names, whatever n is.

Put in orderCompare each pair once

Put the lines in order to build has_duplicate(nums), which returns True when some value sits at two different positions. It compares each pair of positions once. Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • for j in range(i + 1, len(nums)):
    • return False
    • return True
    • def has_duplicate(nums):
    • if nums[i] == nums[j]:
    • for i in range(len(nums)):
    • for j in range(len(nums)):
    • return False

    To recap: nested loops multiply. Two loops over the same n items run the inner body n × n times, or about half that when the inner loop starts at i + 1. Either way, doubling n multiplies the work by about 4.

    Loops that halve

    Can a loop make fewer passes than there are items? It can, if each pass throws away half of what is left. A knockout tournament works this way. With 8 teams, each round sends half the teams home: 8 become 4, then 2, then 1 champion. Three rounds for 8 teams, not eight.

    The loop below does the same with 16 items. It keeps only n, how many items are still in play. Each pass keeps half of them: // divides and rounds down, so 7 // 2 is 3. The loop stops when one item is left. Before you step through, guess the final value of steps.

    Step throughHalving until one is left
    Step 1 of 17
    Line 1 is about to run.
    n = 16
    steps = 0
    while n > 1:
    n = n // 2
    steps += 1
    print(steps)
    Names
    no names yet
    Output
    (nothing printed yet)

    Four passes for 16 items, because 16 halves to 8, 4, 2, 1. That count has a name: log⁡2n\log_2 n, the base-2 logarithm of n, the power you raise 2 to in order to get n. log⁡216=4\log_2 16 = 4 because 2 × 2 × 2 × 2 = 16, and log⁡28=3\log_2 8 = 3, the tournament's three rounds. When n is not a power of 2 (1, 2, 4, 8, 16, and so on), log⁡2n\log_2 n falls between two whole numbers, and this loop stops at log⁡2n\log_2 n rounded down. For 100: 50, 25, 12, 6, 3, 1 is 6 passes, and log⁡2100\log_2 100 is about 6.6.

    A loop that halves barely notices the input growing:

    nPasses of the halving loop
    164
    1006
    1,000,00019
    1,000,000,00029

    A thousand times more data (a million to a billion) adds 10 passes. This shape is labelled O(log n). You will meet it again as binary search in module 6, where each comparison throws away half of a sorted list.

    Halve one by hand, then write the loop yourself.

    On paperHalve 1,000 by hand

    Run the halving loop from the trace above by hand, starting with n = 1000. On paper, write each new value of n (remember that // rounds down) and count the passes until the loop stops.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    passes

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Code itCount the halvings

    Write count_halvings(n), which returns how many times n can be halved with // before it reaches 1. Use a loop and a tally, the way the trace did. Then press Watch it run to see n shrink.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Same n, different counts

    So far the count depended only on n. Some loops stop early, so the count depends on the data too.

    Here is a search that walks the list and returns as soon as it finds the target. It gives back the target's position, or -1 if the target is missing. Before you step through, guess how many passes it needs to find 7 in [4, 9, 7, 1, 5].

    Step throughA search that stops early
    Step 1 of 14
    Line 1 is about to run.
    def find(nums, target):
    steps = 0
    for i in range(len(nums)):
    steps += 1
    if nums[i] == target:
    return i
    return -1
    Names
    no names yet
    Output
    (nothing printed yet)

    The same five items take a different number of passes depending on the target:

    TargetWhere it isPasses
    4position 01
    7position 23
    5position 4, the last5
    8not in the list5

    The best case is the input of size n that needs the fewest steps; the worst case is the one that needs the most. For find on n items, the best case is 1 pass (the target is first) and the worst case is n passes (the target is last or missing). The duplicate check from the parsons puzzle splits the same way: if the first two items match, it stops after 1 comparison; with no repeat it makes all n(n − 1)/2.

    Here is the search as walk, notebook, promise and cost:

    Work it outWhere the search stops

    Using find from the trace above, what is steps when find([8, 3, 6, 3, 9], 3) returns? Type a whole number.

    steps

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Interviews mean the worst case unless they say otherwise. The worst case is a guarantee: whatever the data, find never takes more than n passes. The best case promises nothing, because it needs a lucky input. (There is also an average case, the count on a typical input. It matters for sets and dicts, which the last lesson of this module prices; everywhere else, say the worst case.)

    Quick checkWhich case to say

    An interviewer asks: "How many steps does find take on a list of n items?" Which answer are they looking for?

    Choose one answer, then check.

    Three shapes side by side

    Here are the three loops from this lesson on the same inputs. Each cell is the number of times the loop body runs.

    nOne loopTwo nested loopsHalving loop
    2241
    44162
    88643
    16162564
    1,0001,0001,000,0009

    Read it down one column at a time. Doubling n doubles the one loop, multiplies the nested loops by 4, and adds 1 to the halving loop. At n = 1,000 the three counts are a thousand, a million and nine. That gap is why the cost of an approach decides whether it finishes in time, and the next lesson turns these shapes into the Big O classes you will quote in every round.

    To recap the whole lesson: count passes of the body, not lines. One loop is n, nested loops multiply, halving is about log⁡2n\log_2 n, and when the data changes the count, say the worst case.

    Last, practice saying it. The words you write here are the words you will say in the room.

    Say itSay the cost out loud

    You have written the every-pair has_duplicate (the inner loop starts at i + 1). The interviewer asks: "What does this cost, and what happens if the list gets 10 times longer?" Write what you would say, in a few plain sentences.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Growth rates and Big O