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

Lesson 2 of 3

Growth rates and Big O

Big O says how fast the work grows when the input grows. Keep the biggest term, drop the constants, and read a problem's size limit to know how fast your solution has to be before you write it.

About 1 hour 15 minutes
By the end you can
  • Turn an exact step count such as n2/2 + n into Big O by keeping the biggest term and dropping constants

  • Name the common classes from O(1) to O(n!) with the kind of code that produces each

  • Read a size limit such as n ≤ 105 and say which classes fit in about one second

  • Say how much extra space an algorithm uses, from the size of its notebook

  • State the time and space cost of a solution out loud, without being asked

You open an interview problem: how close are the two closest numbers in a list? Under the examples, a line says the list can hold up to 100,000 numbers. Your first idea is to compare every pair. The last lesson showed how to count that: each pair once is n(n − 1)/2 checks, which is 4,999,950,000 at n = 100,000. Is that a second or an hour? Should you start typing?

Big O is the language for answering that quickly. It answers one question: when the input grows, how fast does the work grow? In a coding interview you are expected to state it for every solution, without being asked. This lesson builds it from step counts you can check by hand, then turns it into a tool: read the size limit in a problem and know how fast your solution must be before you write a line.

Two reminders from the last lesson: a step is one simple operation (a comparison, an addition, reading one item), and n is the size of the input, here the number of items in the list. The cost of a loop is how many times its body runs.

How the work grows

Start with the opening question on four numbers: how close are the two closest? For [9, 2, 7, 4] the answer is 2: 9 and 7 are 2 apart, and so are 2 and 4. Read the numbers as the minutes when events arrived, and the question becomes "how close together did two events land?"

The first plan anyone says out loud: compare every pair. Two tools appear in it. abs(x) is the distance of x from zero, so abs(9 - 2) and abs(2 - 9) are both 7. float("inf") is infinity, a value larger than every number, so the first real gap always replaces it (the same idea as starting a maximum at float("-inf")).

The extra name checks is not part of the answer. It counts the pairs we compare, so the cost is on screen. Before you step through, guess: how many checks does a list of four numbers need?

Step throughComparing every pair
Step 1 of 42
Line 1 is about to run.
def smallest_gap(nums):
best = float("inf")
checks = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
checks += 1
gap = abs(nums[i] - nums[j])
if gap < best:
best = gap
print("checks:", checks)
return best
Names
no names yet
Output
(nothing printed yet)

Four numbers, six checks. The inner loop starts one place right of i, so each pair comes up exactly once: i = 0 has three partners to its right, i = 1 has two, i = 2 has one and i = 3 has none. 3 + 2 + 1 = 6. It is the each-pair-once count from the last lesson: with n numbers it is (n − 1) + (n − 2) + ... + 1, which works out to n(n − 1)/2 checks.

Go slower: Why the sum is n(n − 1)/2

Write the sum for n = 5 forwards and backwards: 4 + 3 + 2 + 1 and 1 + 2 + 3 + 4. Add them column by column. Every column adds to 5, and there are 4 columns, so twice the sum is 5 × 4 = 20 and the sum is 10. In general there are n − 1 columns that each add to n, so the sum is n(n − 1)/2.

Now watch what the count does as the list grows:

Numbers (n)Checks, n(n − 1)/2
46
828
16120
1,000499,500
2,0001,999,000

Each time n doubles, the checks roughly quadruple. From 1,000 to 2,000 numbers, 499,500 checks become 1,999,000, almost exactly four times as many. A single loop over the list behaves differently: double the list, double the work. How the work grows as the input grows is the algorithm's growth rate, and it is what Big O writes down.

Work it outChecks for ten numbers

The pair loop in the trace above checks each pair of numbers exactly once. How many checks does it make on a list of 10 numbers? Type a whole number.

checks

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

Now put the pair loop together yourself. The line that matters most is where the inner loop starts.

Put in orderBuild the pair loop

Put the lines in order to build smallest_gap(nums), which compares every pair of numbers once and returns the smallest distance between two of them. The list has at least two numbers. 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)
    • best = gap
    • return best
    • for j in range(i + 1, len(nums)):
    • best = float("inf")
    • if gap < best:
    • def smallest_gap(nums):
    • gap = abs(nums[i] - nums[j])
    • for j in range(len(nums)):
    • for i in range(len(nums)):
    • best = 0

    Keep the biggest term, drop the constants

    The pair loop makes exactly n(n − 1)/2 checks. So why does everyone call it O(n2), read "order n squared"?

    An exact count depends on what you call a step. Count only the checks and the loop costs n(n − 1)/2. Count all three lines of the inner body and it costs three times that, plus the updates to best, plus the lines outside the loops. A faster laptop changes the seconds again. None of these choices change the shape: double n and every version of the count roughly quadruples.

    Big O keeps only the shape, using two rules.

    Here are both rules at work on two counts, 3n + 5 and n2/2 + n:

    n3n + 5n2/2 + nShare of the n part in n2/2 + n
    10356010 of 60, one sixth
    1003055,100100 of 5,100, about 2%
    1,0003,005501,0001,000 of 501,000, about 0.2%

    At large n the biggest term decides. In 3n + 5 the 5 never grows and the 3 does not change what doubling does, so 3n + 5 is O(n). In n2/2 + n the n part shrinks from a sixth of the total to a rounding error, so n2/2 + n is O(n2). The pair loop, n(n − 1)/2 = n2/2 − n/2, is O(n2) for the same reason.

    Why is it safe to drop a constant, even a big one? Compare 100n with n2/2. At n = 10, 100n is 1,000 and n2/2 is only 50. At n = 200 they are equal, 20,000 each. At n = 1,000, n2/2 is 500,000 against 100,000, and the gap keeps widening. Past some size, the faster-growing count is always bigger, whatever the constants. That is what Big O states: an algorithm is O(n2) when, for large n, its steps are at most some fixed number times n2.

    Big O is an upper limit, so state the smallest class that fits. A loop of n steps is also at most n2 steps, so on paper it is O(n2) too, but saying so hides how cheap it is. When you state a cost, a single loop is O(n).

    Loops in a row add, loops inside loops multiply

    Two loops one after the other add: n + n = 2n steps, which is O(n). A loop inside a loop multiplies: an outer loop of n passes, each running an inner loop of n passes, is n × n = n2 steps. Predict this one before you check it.

    PredictIn a row, or inside

    Type exactly what this prints. print(a, b, c) prints the three values separated by spaces.

    def one_after_another(n):
        steps = 0
        for i in range(n):
            steps += 1
        for j in range(n):
            steps += 1
        return steps
    
    def one_inside_another(n):
        steps = 0
        for i in range(n):
            for j in range(n):
                steps += 1
        return steps
    
    for n in [3, 6]:
        print(n, one_after_another(n), one_inside_another(n))
    

    Now count a whole function on paper and simplify it.

    On paperCount it, then simplify

    On paper, count how many times each loop body runs in this function for a list of n numbers. Count one step for each run of total += x and one for each run of the if line. Add the counts, then turn the total into Big O.

    def summary(nums):
        total = 0
        for x in nums:
            total += x
        bigger = 0
        for a in nums:
            for b in nums:
                if a < b:
                    bigger += 1
        return total, bigger

    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.

    steps for n = 10

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

    To recap: an exact count depends on what you call a step, so Big O keeps only the shape. Keep the fastest-growing term, drop constant factors, add loops that run one after another, and multiply loops that run one inside another.

    The classes you will meet

    Which growth rates actually come up? Counts with the same shape share a class, named by the biggest term: 3n + 5 and 100n are both in the class O(n). Seven classes cover most of the costs you will state, and each has a kind of code that produces it. Two of them use notation worth spelling out. 2n is n twos multiplied together: 23 = 2 × 2 × 2 = 8. n!, read "n factorial", is n × (n − 1) × ... × 1: 3! = 3 × 2 × 1 = 6.

    ClassWhere you meet itWhat more input does
    O(1)reading nums[i], a dict lookup (on average)nothing: the cost stays the same
    O(log n)halving the range each step (binary search)doubling n adds one step
    O(n)one loop over the inputdoubling n doubles the steps
    O(n log n)sortingdoubling n a little more than doubles them
    O(n2)every pair: a loop inside a loopdoubling n multiplies them by 4
    O(2n)every subsetone more item doubles them
    O(n!)every orderingone more item multiplies them by n + 1

    Out loud, interviewers say the classes by name: constant time for O(1), logarithmic for O(log n), linear for O(n), "n log n" for O(n log n), quadratic for O(n2), exponential for O(2n) and factorial for O(n!).

    log n means log base 2: how many times you can halve n before reaching 1, the count the last lesson's halving loop made. 16, 8, 4, 2, 1 is four halvings, so log 16 = 4. The log of a million is about 19.9, which is why binary search over a million sorted items needs only about 20 steps. (In Big O the base of the log does not matter: logs in two different bases differ by a constant factor, and constants are dropped.) Sorting n items takes about n log n steps; module 6 shows why.

    The chart below puts all seven on one picture. Steps go up the side on a log scale: each gridline is 10,000 times the one below, so a count of 4 and a count of 21 trillion fit on the same chart. The table under it gives the steps at the current n and the time, assuming Python does about 10 million simple steps per second (the next section puts that number to work).

    The classes up to n2 stay small on this range. 2n and n! explode. Here is where 2n comes from. A subset is any selection of the items, from none of them to all of them. Each item is either in or out, so every new item doubles the count: every old subset stays, and a copy of each one gains the new item. In the code, each subset is a list, so subsets is a list of lists, and + on two lists builds a new list holding the items of both: ["a"] + ["b"] is ["a", "b"]. Before you step through, guess how many subsets three items have.

    Step throughEvery subset, doubling
    Step 1 of 33
    Line 1 is about to run.
    items = ["a", "b", "c"]
    subsets = [[]]
    for x in items:
    with_x = []
    for s in subsets:
    with_x.append(s + [x])
    subsets = subsets + with_x
    print(x, len(subsets))
    Names
    no names yet
    Output
    (nothing printed yet)

    Orderings grow even faster. Three items have 6 orderings: abc, acb, bac, bca, cab, cba. There are 3 choices for the first place, then 2 for the second, then 1 for the last: 3 × 2 × 1 = 3! = 6. Ten items have 10! = 3,628,800 orderings.

    The class table also works backwards: from how the time changes, you can tell the class.

    Quick checkWhich class, from two timings?

    You time a solution on lists of numbers. A list of 1,000 numbers takes 0.5 seconds. A list of 2,000 numbers takes 2 seconds. Which class does that growth point to?

    Choose one answer, then check.

    To recap: each class has a shape of code behind it. One loop is O(n), halving is O(log n), sorting is O(n log n), every pair is O(n2), every subset is O(2n) and every ordering is O(n!). 2n is fine for 20 items and n! for 10, and both are hopeless at 100.

    From the size limit to the speed you need

    How fast does a solution need to be? Problems state their size limits, for example "1 ≤ n ≤ 105" (105 is 100,000). LeetCode lists them under Constraints; in an interview, you ask. With one rule of thumb, that limit tells you which class to aim for.

    The widget below does the arithmetic for every class at once. It starts at a limit of 100,000; each bar is one class, lime when it fits in a second and coral when it does not.

    Here is what the slider says, plus one size it does not reach, as a table you can carry into the room:

    Largest nMost expensive class that fits
    10O(n!)
    20O(2n)
    100 to 1,000 (102 to 103)O(n2)
    10,000 to 100,000 (104 to 105)O(n log n)
    1,000,000 (106)O(n)
    1,000,000,000 (109)O(log n)

    Read it from the constraint to the class. The numbers are rough, so a class right at the line is borderline. But a class that misses by a factor of 1,000, like n2 at 105, cannot be rescued by tuning. The last row usually means n is one big number, not a list: a single walk to 109 is 109 steps, about 100 seconds. Even O(n) is too slow there, and halving, O(log n), is the usual way in.

    Work it outHow long would it take?

    A problem says 1 ≤ n ≤ 105. Your plan compares every pair, about n2/2 checks. Treat each check as one simple step, and assume Python does 10 million (107) simple steps per second. How many seconds would the largest input take?

    seconds

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

    Our pair loop fails this budget. The opening problem allows 100,000 numbers, so the pair loop would make 4,999,950,000 checks. By the rule of thumb that is about 500 seconds: neither a second nor an hour, and far too slow. We need O(n log n), and the class table says where O(n log n) usually comes from: sorting.

    After sorting, the closest pair is always side by side. Take three sorted numbers a ≤ b ≤ c. The outer gap c − a equals (c − b) + (b − a), so it is at least as big as either neighbor gap. A pair that skips over a number is never closer than the neighbor pairs inside it. So we sort once and check only neighbors. Before you step through, guess how many checks four numbers need now.

    Step throughSort first, then check neighbors
    Step 1 of 22
    Line 1 is about to run.
    def smallest_gap(nums):
    ordered = sorted(nums)
    best = float("inf")
    checks = 0
    for i in range(1, len(ordered)):
    checks += 1
    gap = ordered[i] - ordered[i - 1]
    if gap < best:
    best = gap
    print("checks:", checks)
    return best
    Names
    no names yet
    Output
    (nothing printed yet)

    Now write it yourself, with a twist: return the pair, not the gap.

    Code itThe closest pair, fast

    Write closest_pair(nums), which returns the two closest numbers as a tuple (smaller, larger). The list has at least two numbers. If several pairs are equally close, return the one with the smallest numbers. Sort first and check only neighbors: the last test gives you 15,001 numbers and 1 second, and comparing every pair takes several seconds. Then press Watch it run.

    ⌘+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.

    Space: how big the notebook gets

    Time counts steps. What about memory? Space complexity is the size of the notebook: how much extra memory the algorithm keeps as n grows, beyond the input it was handed. The rules are the same: keep the biggest term, drop constants.

    The two notebooks below see the same walk over four days of order counts. One keeps a single number; the other keeps a list. Before you step through, guess what running holds at the end.

    Step throughTwo notebooks, one walk
    Step 1 of 18
    Line 1 is about to run.
    orders = [12, 30, 7, 25]
    total = 0
    running = []
    for x in orders:
    total += x
    running.append(total)
    print(total, running)
    Names
    no names yet
    Output
    (nothing printed yet)

    total is O(1) space: one number, however long the list. running is O(n): one item per pass. The two closest-pair solutions differ the same way. The pair loop keeps five names (best, checks, i, j, gap) whatever n is, so it uses O(1) extra space. The sorted version builds ordered, a copy with n items, so it uses O(n). The faster solution here also uses more memory, though the speed comes from sorting; the copy is there so the caller's list stays unchanged. Often the memory is exactly what buys the speed: the next lesson speeds up a duplicate check with a set that remembers what the walk has seen, and sets and dicts are the main tool of module 3.

    Quick checkHow big does the notebook get?

    How much extra space does this function use, for a list of n numbers?

    def has_duplicate(nums):
        seen = set()
        for x in nums:
            if x in seen:
                return True
            seen.add(x)
        return False

    Choose one answer, then check.

    Last, say it the way you would in the room.

    Say itSay the cost out loud

    You have just written the pair loop for the smallest gap (two nested loops, j starting at i + 1). Say its cost the way you would to an interviewer, without being asked. Then answer the follow-up: "Can you do better if n can be 100,000?"

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: What Python operations cost