Recognise O(1), O(log n), O(n), O(n log n), O(n^2) and O(2^n) and what each means at real sizes.
Use it when you must decide whether an approach fits a time limit, or how large an input a method can take. Signal words: will it fit, how large can n be, about 10^8 steps a second.
Start the step budget: steps per second times seconds. Use 100,000,000 a second as a planning estimate.
Step count the steps of the class at the real n, with a 64-bit counter and a cap for huge counts.
Stop compare the count with the budget. Divide by the rate for a time.
It does not give a promise. The rate depends on the machine and the language, and constants inside the steps matter, so keep a margin.
Cost: the check is one formula. It replaces a run that could take hours.
In this lesson you put numbers on the classes. You learn what input size each class can handle in about a second, and you decide whether an approach fits a time limit before you write it.
You work on a monitoring system. A nightly job reads 1,000,000 events and must finish within 1 second on one machine. The team estimates that a simple step takes about 10 nanoseconds, so the machine does about 100,000,000 steps a second.
Three approaches are on the table. The first compares every pair of events. The second sorts the events and compares neighbours. The third reads the events once.
Your team lead says: Tell me which approaches can fit the second, before anyone writes code.
So the task is this: count the steps of each approach at 1,000,000 events, and compare with the budget.
A delivery van drives at a fixed speed, and the driver has one hour. Before the trip, the driver multiplies speed by time to learn how far the van can go. A job beyond that distance does not fit, however well the van is driven.
The step rate is the speed, the time limit is the hour, and the steps of an approach are the distance. You learn what fits before you start.
Like a van with one hour: speed times time is how far it can go, and a longer job does not fit.
Before you write code, work out one count by hand. The sorting approach makes about n steps for each halving, so n times the number of halvings.
Solve it by hand: Steps of an n log n method at 1,000 events. The hand-solve sheet loads in your browser.
Each count comes from the class formula, which was checked against counted runs in the first two lessons.
| Approach | Class | Steps at n = 1,000 |
|---|---|---|
| Read the events once | O(n) | 1,000 |
| Sort, then compare neighbours | O(n log n) | 9,000 |
| Compare every pair | O(n squared) | 1,000,000 |
At 1,000 events, all three finish in well under a millisecond at 100,000,000 steps a second.
Start with a correct version. Compare every pair of events, and report a pair that matches.
def has_match(events):
n = len(events)
for a in range(n): # each event
for b in range(a + 1, n): # every later event
if events[a] == events[b]: # one step
return True
return FalseIt is correct. For a million events with no match, it makes n(n-1)/2 steps.
Now check the real size.
The job has 1,000,000 events, and the machine does about 100,000,000 steps a second.
Here is the count:
The pair version is 5,000 times over the budget. The sort and the single pass both fit.
Predict the cost
Q A job makes 500,000,000,000 steps at 100,000,000 steps a second. About how long does it take?
Answer: C
500,000,000,000 / 100,000,000 is 5,000 seconds, about 83 minutes.
You decided this with a count and a division, before any code ran.
Can you know the largest input for a class without testing? Turn the question around. Fix the budget, 100,000,000 steps for one second, and ask how large n can be.
| Class | Largest n in one second at 100,000,000 steps |
|---|---|
| O(log n) | any n you can store |
| O(n) | 100,000,000 |
| O(n log n) | 4,545,454 |
| O(n squared) | 10,000 |
| O(n cubed) | 464 |
| O(2 to the n) | 26 |
These limits come from running a search for the largest n whose step count fits the budget. Each step down in class cuts the reachable input by a large factor, and the last two classes barely reach beyond a few hundred items.
Race: Steps of five classes as n grows. The operation counter loads in your browser.
The race counts steps at n = 10, 20, 30 and 40. At 40, a linear count is 40, n log n is 200, n squared is 1,600, and 2 to the n is 1,099,511,627,776.
The largest n in one second: a hundred million for linear, ten thousand for n squared, and only twenty six for two to the n.
Exercise · Predict the output: How large can n be?. A quadratic job may make at most 1,000 steps. This code finds the largest n that fits and prints it with its step count. What does it print?
budget = 1000
n = 0
while (n + 1) * (n + 1) <= budget:
n += 1
print(n, n * n)How long does the pair version take at 100,000 events? Its steps are 4,999,950,000. The machine does 100,000 steps in each millisecond. The player divides, rounding up, and asks you to predict.
Dry run: Predict each step: how long the pair version takes. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Step | Value |
|---|---|
| Steps | 4,999,950,000 |
| Steps in one millisecond | 100,000 |
| Milliseconds, rounded up | 50,000 |
That is 50 seconds for a time limit of 1 second.
The 100,000,000 steps a second is an estimate. Here are loops timed on one laptop, each doing one addition per pass, best of 5 runs. Your figures will differ.
| Language | Measured steps a second |
|---|---|
| Compiled (C++ and Java) | about 1,200,000,000 |
| JavaScript (compiled as it runs) | about 1,000,000,000 |
| Python | about 50,000,000 |
The n squared limit for one second moves with the speed: about 7,000 items in Python, 10,000 at the planning rate, and about 35,000 in a compiled language. The class sets the order of magnitude, and the language moves it by a constant factor.
Here is the rule behind every limit in this lesson. Both templates use it.
Divide the time limit's step budget by the steps per input item for each class, and the class tells you the largest n it can handle.
The step budget is the step rate times the time limit. A class fits when its step count at the real n is at most the budget.
Use it when you must decide whether an approach fits a time limit, or how large an input a method can take. Signal words: will it fit, how large can n be, about 10^8 steps a second.
Start: the step budget: steps per second times seconds. Use 100,000,000 a second as a planning estimate.
Step: count the steps of the class at the real n, with a 64-bit counter and a cap for huge counts.
Stop: compare the count with the budget. Divide by the rate for a time.
It does not give a promise. The rate depends on the machine and the language, and constants inside the steps matter, so keep a margin.
Cost: the check is one formula. It replaces a run that could take hours.
The classes are numbered 0 log n, 1 n, 2 n log n, 3 n squared, 4 n cubed and 5 2 to the n. Here log n is the number of halvings, floor of log2 n. Huge counts are capped at 4 × 10^18 so they never overflow.
def steps_for(kind, n):
cap = 4000000000000000000
# [1] The number of halvings: floor of log2 n, and 0 when n is 0.
halvings = n.bit_length() - 1 if n > 0 else 0
# [2] O(log n) and O(n): read them straight off.
if kind == 0:
return halvings
if kind == 1:
return n
# [3] O(n log n): n steps for each halving.
if kind == 2:
return n * halvings
# [4] O(n squared) and O(n cubed): a product, capped before it can overflow.
if kind == 3:
return n * n
if kind == 4:
return cap if n > 1000000 else n * n * n
# [5] O(2 to the n): capped above 61, where it would pass 64 bits.
return cap if n > 61 else 2 ** npublic long stepsFor(int kind, int n) {
long cap = 4000000000000000000L;
// [1] The number of halvings: floor of log2 n, and 0 when n is 0.
long halvings = n > 0 ? 31 - Integer.numberOfLeadingZeros(n) : 0;
long m = n;
// [2] O(log n) and O(n): read them straight off.
if (kind == 0) {
return halvings;
}
if (kind == 1) {
return m;
}
// [3] O(n log n): n steps for each halving.
if (kind == 2) {
return m * halvings;
}
// [4] O(n squared) and O(n cubed): a product, capped before it can overflow.
if (kind == 3) {
return m * m;
}
if (kind == 4) {
return n > 1000000 ? cap : m * m * m;
}
// [5] O(2 to the n): capped above 61, where it would pass 64 bits.
return n > 61 ? cap : 1L << n;
}long long stepsFor(int kind, int n) {
long long cap = 4000000000000000000LL;
// [1] The number of halvings: floor of log2 n, and 0 when n is 0.
long long halvings = n > 0 ? 31 - __builtin_clz(n) : 0;
long long m = n;
// [2] O(log n) and O(n): read them straight off.
if (kind == 0) {
return halvings;
}
if (kind == 1) {
return m;
}
// [3] O(n log n): n steps for each halving.
if (kind == 2) {
return m * halvings;
}
// [4] O(n squared) and O(n cubed): a product, capped before it can overflow.
if (kind == 3) {
return m * m;
}
if (kind == 4) {
return n > 1000000 ? cap : m * m * m;
}
// [5] O(2 to the n): capped above 61, where it would pass 64 bits.
return n > 61 ? cap : 1LL << n;
}function stepsFor(kind, n) {
const cap = 4000000000000000000n;
// [1] The number of halvings: floor of log2 n, and 0 when n is 0.
const halvings = n > 0 ? 31 - Math.clz32(n) : 0;
const m = BigInt(n);
// [2] O(log n) and O(n): read them straight off.
if (kind === 0) {
return Number(BigInt(halvings));
}
if (kind === 1) {
return Number(m);
}
// [3] O(n log n): n steps for each halving.
if (kind === 2) {
return Number(m * BigInt(halvings));
}
// [4] O(n squared) and O(n cubed): a product, capped before it can overflow.
if (kind === 3) {
return Number(m * m);
}
if (kind === 4) {
return Number(n > 1000000 ? cap : m * m * m);
}
// [5] O(2 to the n): capped above 61, where it would pass 64 bits.
return Number(n > 61 ? cap : 1n << m);
}Rebuild the template: put its lines back in order. Loads in your browser.
Divide the steps by the steps in one millisecond, and round up, so a partial millisecond counts as one.
def milliseconds_needed(steps, steps_per_ms):
# [1] Round up: any part of a millisecond counts as a whole one.
whole = (steps + steps_per_ms - 1) // steps_per_ms
# [2] Return the time in milliseconds.
return wholepublic long millisecondsNeeded(long steps, int stepsPerMs) {
// [1] Round up: any part of a millisecond counts as a whole one.
long whole = (steps + stepsPerMs - 1) / stepsPerMs;
// [2] Return the time in milliseconds.
return whole;
}long long millisecondsNeeded(long long steps, int stepsPerMs) {
// [1] Round up: any part of a millisecond counts as a whole one.
long long whole = (steps + stepsPerMs - 1) / stepsPerMs;
// [2] Return the time in milliseconds.
return whole;
}function millisecondsNeeded(steps, stepsPerMs) {
// [1] Round up: any part of a millisecond counts as a whole one.
const whole = (BigInt(steps) + BigInt(stepsPerMs) - 1n) / BigInt(stepsPerMs);
// [2] Return the time in milliseconds.
return Number(whole);
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The job that is called fast enough. This check says whether a job fits a time limit. It says yes to a job that runs 10.5 milliseconds against a limit of 10. Which line is wrong?
def fits(steps, steps_per_ms, limit_ms):
needed = steps // steps_per_ms
return needed <= limit_msFrom steps to time: add the rate minus one, then divide by the rate, so any part of a millisecond counts as a whole one.
You can decide any approach in four steps.
Exercise · Break it: Find the size this check turns away. This check says a quadratic job fits when its steps stay under the budget. Find a size and a budget where it gives the wrong answer.
def fits_quadratic(n, budget):
steps = n * n
return steps < budgetA job sorts 5,000,000 events with a method that makes n × 23 steps (23 halvings, rounding up). That is 115,000,000 steps.
Template 2 at 100,000 steps a millisecond gives 1,150 milliseconds. It misses a limit of 1 second by 15 percent, so it needs a faster rate or a smaller n.
Real data brings edge cases.
With n = 0, every class makes 0 steps except 2 to the n, which makes 1 in a model where an empty input still starts the work. Template 1 gives 0 for the log, linear and quadratic classes at n = 0, and 1 for kind = 5.
For kind = 4, n = 2000000, the count n × n × n is 8 × 10^18, close to the 64-bit limit of 9.2 × 10^18, and a little more would wrap. The template returns a cap of 4 × 10^18 instead, which is already far over any budget.
For the quadratic class at n = 10000 the count is 100,000,000, exactly the budget. It fits, and one more item does not. A real machine has no such sharp edge, so keep a margin.
For kind = 1, n = 1000000000 the count is 1,000,000,000, ten times the budget for one second. A million items is easy, and a billion is ten seconds at the planning rate.
This version uses the Python rate measured on one laptop, 50,000,000 steps a second, to say n squared fits only up to 7,000 items in any language.
Counterexample: a compiled loop on the same laptop did about 1,200,000,000 steps a second, so n squared fits up to about 35,000 items there. Pick the rate for the language you will use, and state it.
This version says any code with at most 100,000,000 steps always finishes in a second.
Counterexample: a step that sorts a list is not a simple step. Timed on one laptop, Python added two small integers in about 7 nanoseconds and sorted 1,000 integers in about 30 microseconds, roughly 4,000 times longer. A count of 100,000,000 such lines is far over a second. Count simple steps, and keep a margin.
A limit read as a promise: sorting a thousand numbers took about 4,000 times longer than adding two on one laptop, so steps are not time.
This version says n log n and n squared are both fast, because both are polynomial-looking.
Counterexample: at 1,000,000 items n log n is 19,000,000 steps and n squared is 1,000,000,000,000. One fits a second, the other takes hours. At 1,000 items the two are 9,000 and 1,000,000, and both fit.
This version holds the step count in a 32-bit integer.
Counterexample: n squared at 100,000 is 10,000,000,000, above the 32-bit limit of 2,147,483,647. The count wraps and the check says the job fits. Use a 64-bit integer.
The budget rule counts simple steps. A job that makes 1,000 network calls is not decided by a step count, because one call takes milliseconds and not nanoseconds.
For such a job, multiply the number of calls by the time of one call. The class still tells you how the number of calls grows.
Your team lead brings three product changes. Each one asks whether an approach fits.
The limit becomes 10 seconds, so the budget is 1,000,000,000 steps. O(n) reaches 1,000,000,000, O(n log n) reaches 40,000,000, and O(n squared) reaches 31,622. A tenfold budget gives n squared only a threefold larger input.
On a machine ten times slower, the budget is 10,000,000 steps. O(n log n) then reaches 526,315 events, and O(n squared) reaches 3,162. The class decides which approach survives.
A job sorts batches one after another. Five batches of 1,000,000 events cost 5 × 19,000,000 = 95,000,000 steps, within the budget of one second. One batch of 5,000,000 events costs 110,000,000 steps with floor halvings, and does not fit.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you decide whether an approach fits a time limit. Give what n each class handles in a second, then say why the rate is only an estimate. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I take the step budget, about 100,000,000 steps for each second. I count the steps of the approach at the real n and divide.
In a second, O(n) handles about 100 million items. O(n log n) handles about 4.5 million, O(n squared) about 10,000 and O(2 to the n) about 26.
The rate is an estimate that moves with the language and the machine. So I keep a margin and measure the real code when it is close.
To decide whether an approach fits a time limit, I work out the step budget. A simple step takes about 10 nanoseconds, so a machine does about 100 million steps in a second. That is an estimate, and I measure it when it matters.
Then I count the steps of the approach at the real input size, with a 64-bit counter. In one second, a linear method handles about 100 million items and n log n about 4.5 million. N squared handles about 10,000, n cubed about 460, and 2 to the n only about 26.
If the count is within the budget, it fits. I divide steps by the rate for a time. For a million events, the pair method makes 500 billion steps, which is more than an hour. Sorting makes 19 million, which is under a fifth of a second.
I keep a margin, because the language and the machine move the rate by a constant factor.
Checkpoint · Common classes, felt
Q1/10 As a planning estimate, about how many simple steps does a machine do in one second?
Answer: B
A simple step takes about 10 nanoseconds, so about 100,000,000 steps fit in a second. It is an estimate.
Q2/10 The time limit is 3 seconds at 100,000,000 steps a second. What is the step budget?
Answer: B
Budget is the rate times the time limit: 3 × 100,000,000.
Q3/10 In one second at the planning rate, about how large an n can an O(n squared) method handle?
Answer: C
n squared must stay at most 100,000,000, so n is at most 10,000.
Q4/10 In one second, which input size fits an O(n log n) method best?
Answer: B
n times the number of halvings must stay at most 100,000,000. The limit is 4,545,454.
Q5/10 About how large an n can an O(2 to the n) method handle in one second?
Answer: C
2 to the 26 is 67,108,864 and 2 to the 27 is 134,217,728, which is over the budget.
Q6/10 A job makes 10,000,000,000 steps at 100,000,000 steps a second. About how long does it run?
Answer: C
10,000,000,000 / 100,000,000 is 100.
Q7/10 On one laptop Python did about 50 million loop steps a second and a compiled language about 1.2 billion. What does that do to the n squared limit?
Answer: B
The limit scales with the square root of the rate. The class stays n squared.
Q8/10 1,000,000 events are sorted with about 19,000,000 steps, and compared in pairs with about 500,000,000,000 steps. Which fits a 1-second limit?
Answer: A
The sort needs 0.19 seconds. The pair version needs about 5,000 seconds.
Q9/10 Why should a step counter for n squared at n = 100,000 be a 64-bit integer?
Answer: B
A wrapped count could make a slow job look as if it fits.
Q10/10 A job needs 120,000,000 steps and the budget is 100,000,000. What should you do?
Answer: B
The rate depends on the machine. Within a small factor of the budget, measure. Over the budget, plan on a better method.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Time limit or not | Rides | Easy | Count how many jobs fit a step budget |
| 2 | Choose the largest feasible input | Bank | Medium | The largest n each class can handle |
| 3 | Sorting five million events | Ads | Medium | Sum the passes of many sorts, then turn steps into time |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.