Turn a statement into inputs, outputs and edge rules, and read the time budget from the constraints with the 10^8 rule.
Use it when you meet any new statement. Signal words: constraints, input size, time limit, edge cases.
Start read the input and output formats, then the limits.
Step turn n into a class with Template 1 and the values into a width with Template 2.
Stop list the edge cases the ranges allow: the smallest n, the extreme values, equal values and the empty answer.
It does not pick the method. It tells you which methods are too slow or too small.
Cost: two small checks and a short list. A minute of reading saves an hour of rewriting.
In this lesson you learn to read a problem statement as an engineer reads a plan. You find what the task reads and returns, you turn the limits into a time budget, and you list the edge cases before you write any code.
You work on the build system behind an app. A teammate pastes a task into the team chat. It says: given the duration in seconds of every build today, report whether any two builds took exactly the same time. Below the task sit a few lines of limits: up to 200,000 builds, and each duration up to 1,000,000,000 seconds.
Your team lead says: Before you write any code, tell me three things. What does the task read, what must it return, and how slow may a solution be?
So the task is to read the statement the way an engineer reads a plan, and to get a time budget from the limits.
A lift has a sign inside. It lists the floors it serves, where it stops, and a maximum load. You read the sign before you step in, because the lift will not carry more than it says.
The floors are the inputs, the stop is the output, and the maximum load is the constraints. You check the sign before you start.
Like the sign in a lift: floors are the inputs, the stop is the output, and the maximum load is the constraints.
Before you read faster, practise one small decision by hand. Given an input size, find the slowest class of method that still fits the time limit.
Solve it by hand: Which class fits 1,000 items. The hand-solve sheet loads in your browser.
Each answer comes from a line of the statement. The last three come from the limits.
| Question | Answer from the statement |
|---|---|
| What does it read? | A list durations of whole numbers |
| What does it return? | True or false: is any value repeated |
| How large is n? | Up to 200,000 builds |
| How large is a value? | Up to 1,000,000,000 seconds |
| What if nothing repeats? | Return false |
| What if there is one build? | There is no pair, so return false |
Five answers, and no code yet.
Start with a correct version. Compare every pair of builds and report true when two are equal.
def has_repeat(durations):
n = len(durations)
for a in range(n): # each build
for b in range(a + 1, n): # every later build
if durations[a] == durations[b]: # one check
return True
return FalseIt is correct. If no duration repeats, it makes n(n-1)/2 checks.
Exercise · Predict the output: How many checks before it stops?. The pair version stops at the first equal pair. The code counts its checks on five build durations. What does it print?
durations = [5, 3, 9, 3, 8]
n = len(durations)
checks = 0
found = False
for a in range(n):
for b in range(a + 1, n):
checks += 1
if durations[a] == durations[b]:
found = True
break
if found:
break
print(checks)Now check the real size.
The task has 200,000 builds, and a machine does about 100,000,000 simple steps in a second.
Here is the count:
The limits already told you this. With n at 200,000, a method that compares every pair cannot finish.
Predict the cost
Q A task allows 200,000 items and the machine does 100,000,000 steps a second. A method compares every pair, about 20,000,000,000 checks. About how long does it take?
Answer: C
20,000,000,000 divided by 100,000,000 is 200 seconds.
You decided this from the statement alone, before any code ran.
Can you tell the right class from the constraints? Turn the question around. Fix the budget, 100,000,000 steps for one second, and ask which class each size of n allows.
| If n is at most | The slowest class that fits |
|---|---|
| 26 | O(2 to the n) |
| 464 | O(n cubed) |
| 10,000 | O(n squared) |
| 4,545,454 | O(n log n) |
| 100,000,000 | O(n) |
Each limit comes from running the check in Template 1 at the edges, for example 464 cubed is 99,897,344 and 465 cubed is 100,544,625. The lesson Common classes, felt explains the table and how the language changes it.
Race: Steps of three methods for the repeated-duration task. The operation counter loads in your browser.
The race counts the steps of three methods for the repeated-duration task, at 1,000, 10,000, 100,000 and 200,000 builds. At 200,000 the pair version makes 19,999,900,000 checks, the sort version 3,400,000 steps, and a single pass over a set about 200,000.
Exercise · Put it in order: Sort, then compare neighbours. Arrange the lines into a function that reports whether any two durations are equal. It sorts a copy, then compares each build with the one before it.
def has_repeat(durations):
ordered = sorted(durations)
for i in range(1, len(ordered)):
if ordered[i] == ordered[i - 1]:
return True
return False
for i in range(len(ordered)):From a constraint to a class: 26 allows 2 to the n, 464 allows n cubed, and 10,000 allows n squared.
Which class fits 200,000 builds? Template 1 tries the slowest class first and returns the first one whose count fits the budget. The player asks you to predict.
Dry run: Predict each step: which class fits 200,000 items. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Check | Count at n = 200,000 | Fits 100,000,000? |
|---|---|---|
| 2 to the n | far over | no |
| n cubed | far over | no |
| n squared | 40,000,000,000 | no |
| n log n | 3,400,000 | yes |
So class 2, n log n, is the slowest class that fits.
The size of a value matters as much as the size of n. Each value is at most 1,000,000,000, and a total of 200,000 of them could reach 200,000,000,000,000. That is far above the 32-bit limit of 2,147,483,647, so a total needs 64 bits.
Here is the rule behind this lesson. Both templates use it. It is also the 10^8 rule at work: about 100,000,000 simple steps fit in a second.
The size of n in the constraints names the slowest class that fits the time limit, and the range of the values names the integer width you need.
The routine has five questions. Ask them in order, before you write code.
Use it when you meet any new statement. Signal words: constraints, input size, time limit, edge cases.
Start: read the input and output formats, then the limits.
Step: turn n into a class with Template 1 and the values into a width with Template 2.
Stop: list the edge cases the ranges allow: the smallest n, the extreme values, equal values and the empty answer.
It does not pick the method. It tells you which methods are too slow or too small.
Cost: two small checks and a short list. A minute of reading saves an hour of rewriting.
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. Each check guards n first, so the product is never computed where it could overflow.
def slowest_fitting_class(n):
budget = 100000000
# [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] Class 5, 2 to the n: only n up to 26 can fit, so a larger n is skipped.
if n <= 26 and 2 ** n <= budget:
return 5
# [3] Class 4, n cubed: guard n first so the product cannot overflow.
if n <= 1000 and n * n * n <= budget:
return 4
# [4] Class 3, n squared: guard n first so the product cannot overflow.
if n <= 100000 and n * n <= budget:
return 3
# [5] Class 2, n log n.
if n * halvings <= budget:
return 2
# [6] Class 1, n.
if n <= budget:
return 1
# [7] Class 0, log n, fits every n you can store.
return 0public int slowestFittingClass(int n) {
long budget = 100000000L;
// [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] Class 5, 2 to the n: only n up to 26 can fit, so a larger n is skipped.
if (n <= 26 && (1L << n) <= budget) {
return 5;
}
// [3] Class 4, n cubed: guard n first so the product cannot overflow.
if (n <= 1000 && m * m * m <= budget) {
return 4;
}
// [4] Class 3, n squared: guard n first so the product cannot overflow.
if (n <= 100000 && m * m <= budget) {
return 3;
}
// [5] Class 2, n log n.
if (m * halvings <= budget) {
return 2;
}
// [6] Class 1, n.
if (m <= budget) {
return 1;
}
// [7] Class 0, log n, fits every n you can store.
return 0;
}int slowestFittingClass(int n) {
long long budget = 100000000LL;
// [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] Class 5, 2 to the n: only n up to 26 can fit, so a larger n is skipped.
if (n <= 26 && (1LL << n) <= budget) {
return 5;
}
// [3] Class 4, n cubed: guard n first so the product cannot overflow.
if (n <= 1000 && m * m * m <= budget) {
return 4;
}
// [4] Class 3, n squared: guard n first so the product cannot overflow.
if (n <= 100000 && m * m <= budget) {
return 3;
}
// [5] Class 2, n log n.
if (m * halvings <= budget) {
return 2;
}
// [6] Class 1, n.
if (m <= budget) {
return 1;
}
// [7] Class 0, log n, fits every n you can store.
return 0;
}function slowestFittingClass(n) {
const budget = 100000000;
// [1] The number of halvings: floor of log2 n, and 0 when n is 0.
const halvings = n > 0 ? 31 - Math.clz32(n) : 0;
// [2] Class 5, 2 to the n: only n up to 26 can fit, so a larger n is skipped.
if (n <= 26 && 2 ** n <= budget) {
return 5;
}
// [3] Class 4, n cubed: guard n first so the product cannot overflow.
if (n <= 1000 && n * n * n <= budget) {
return 4;
}
// [4] Class 3, n squared: guard n first so the product cannot overflow.
if (n <= 100000 && n * n <= budget) {
return 3;
}
// [5] Class 2, n log n.
if (n * halvings <= budget) {
return 2;
}
// [6] Class 1, n.
if (n <= budget) {
return 1;
}
// [7] Class 0, log n, fits every n you can store.
return 0;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The size that fits too well. For n = 1,000 this function says that an n-cubed method fits the budget. It does not. Which line is wrong?
def slowest_fitting_class(n):
budget = 100000000
halvings = n.bit_length() - 1 if n > 0 else 0
if n <= 26 and 2 ** n <= budget:
return 5
if n <= 1000 and n * n <= budget:
return 4
if n <= 100000 and n * n <= budget:
return 3
if n * halvings <= budget:
return 2
if n <= budget:
return 1
return 0Multiply the number of values by the largest value. If the product passes the largest 32-bit integer, the total needs 64 bits.
def needs_wide_total(count, biggest):
# [1] The largest total the data can make, held in a wide value where the language needs one.
largest_total = count * biggest
# [2] A 32-bit integer stops at 2,147,483,647; above that the total needs 64 bits.
return 1 if largest_total > 2147483647 else 0public int needsWideTotal(int count, int biggest) {
// [1] The largest total the data can make, held in a wide value where the language needs one.
long largestTotal = (long) count * biggest;
// [2] A 32-bit integer stops at 2,147,483,647; above that the total needs 64 bits.
return largestTotal > 2147483647L ? 1 : 0;
}int needsWideTotal(int count, int biggest) {
// [1] The largest total the data can make, held in a wide value where the language needs one.
long long largestTotal = (long long)count * biggest;
// [2] A 32-bit integer stops at 2,147,483,647; above that the total needs 64 bits.
return largestTotal > 2147483647LL ? 1 : 0;
}function needsWideTotal(count, biggest) {
// [1] The largest total the data can make, held in a wide value where the language needs one.
const largestTotal = count * biggest;
// [2] A 32-bit integer stops at 2,147,483,647; above that the total needs 64 bits.
return largestTotal > 2147483647 ? 1 : 0;
}Rebuild the template: put its lines back in order. Loads in your browser.
Does a total need 64 bits? Multiply the count by the largest value, and compare with 2,147,483,647.
You can read any statement in five steps.
Exercise · Break it: Find the durations this check misses. This check reports a repeat when two builds next to each other took the same time. Find a list where it gives the wrong answer.
def has_repeat(durations):
for i in range(1, len(durations)):
if durations[i] == durations[i - 1]:
return True
return FalseA task adds the durations of all builds. The limits are 200,000 builds of at most 3,600 seconds each.
Template 1 at n = 200,000 gives class 2, so a sort fits. Template 2 gives 720,000,000, which is below 2,147,483,647, so 0: a 32-bit total is enough. If each build could take 1,000,000,000 seconds, the largest total is 200,000,000,000,000, and the answer is 1: use 64 bits.
Real data brings edge cases. The constraint ranges name them.
With durations = [900] there is one build and no pair, so the answer is false. A loop that starts at the second item must not read past the end.
With durations = [3, 1, 2] no value repeats, and the task says to return false. Decide this answer before you code, because a loop that never returns inside leaves it to the last line.
With durations = [1000000000, 1000000000, 1000000000], three values of 1,000,000,000 repeat. Their sum is 3,000,000,000, above the 32-bit limit, so a task that adds them needs a 64-bit total.
With 200,000 builds that all took 5 seconds, the first pair repeats at once. A method that stops at the first match is fast here, and a method that scans everything is not. Good tests include both shapes.
This version reads the five builds in the example, sees that comparing every pair is instant, and ships it.
Counterexample: the limits allow 200,000 builds. With 200,000 different durations the pair version makes 19,999,900,000 checks, about 200 seconds at the planning rate. The limits, not the examples, set the size.
This version adds durations in a 32-bit integer.
Counterexample: three builds of 1,000,000,000 seconds add up to 3,000,000,000. In a 32-bit integer that wraps to -1,294,967,296, so the task reports a negative total. Template 2 flags it before you run anything.
Three builds of a billion seconds add up to three billion, which wraps to a negative number in 32 bits.
This version returns max(durations) for the slowest build and never checks for an empty list.
Counterexample: with durations = [], Python raises ValueError. Read the lower limit of n. If it is 0, decide the answer for an empty list first.
This version multiplies the number of values by the largest value in a 32-bit int.
Counterexample: in Java, 100000 * 100000 in an int gave 1,410,065,408, which is below 2,147,483,647, so the check says 32 bits are enough. The real largest total is 10,000,000,000. Template 2 casts to long before it multiplies.
A task allows at most 20 items and asks for the best choice among all subsets. Template 1 at n = 20 returns class 5: 2 to the 20 is 1,048,576 steps, which fits easily.
Here the limits say a slow method is intended. A faster method would take more time to write and gain nothing.
Your team lead brings three product changes. Each one moves the limits.
The time limit becomes 5 seconds, so the budget is 500,000,000 steps. An n squared method then reaches n = 22,360 instead of 10,000, only a little more than twice as far. A budget five times larger does not change the class that fits 200,000.
The task now allows 1,000,000 builds. Template 1 returns 2: n log n is 19,000,000 steps, which fits. The pair version would make 499,999,500,000 checks. The class that fits does not change.
Each duration may reach 1,000,000,000,000,000,000. One value still fits a 64-bit integer, whose limit is 9,223,372,036,854,775,807. A sum of ten such values is 10,000,000,000,000,000,000, which does not fit. The constraints now call for a wider type or a different method.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you read a new problem. Name the five questions, then say how the constraints tell you the class and the integer width. 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 practised it.
I read what the task takes in and what it returns. Then I read the limits before I think about a method.
At about 100 million steps a second, n of 200,000 rules out n squared and allows n log n. The size of the values tells me whether a total needs 64 bits.
Last, I list the edge cases the ranges allow: the smallest n, the extreme values, equal values and an empty answer.
Before I code, I read the statement in five questions.
What does it read? What does it return, and what does it return when nothing qualifies? How large is n, and how large is a value? What are the edge cases?
The limits answer three of them. A machine does about 100 million simple steps a second. So n up to 10,000 allows n squared, n up to 4.5 million allows n log n, and n up to 100 million allows a single pass.
For 200,000 items, comparing every pair is 20 billion checks, about 200 seconds, so I sort or use a set instead.
I multiply the number of values by the largest value. If it passes about 2 billion, I use 64-bit integers.
Last, I write the edge cases from the ranges.
Checkpoint · Reading problems and constraints
Q1/10 Which part of a statement tells you how slow a method may be?
Answer: B
The constraints give the largest n and the largest values. The examples are small on purpose.
Q2/10 As a planning estimate, how many simple steps does a machine do in a second?
Answer: B
The lesson uses about 100,000,000 steps a second.
Q3/10 A task allows n up to 10,000. Which is the slowest class that fits one second?
Answer: B
10,000 squared is exactly 100,000,000. n cubed would be 1,000,000,000,000.
Q4/10 A task allows n up to 200,000. About how many checks does comparing every pair make?
Answer: C
n(n-1)/2 is 19,999,900,000, about 200 seconds at the planning rate.
Q5/10 A task allows n up to 26. Which class still fits one second?
Answer: C
2 to the 26 is 67,108,864, below 100,000,000.
Q6/10 A task has 100,000 values of at most 100,000 each, and you add them. Which integer do you need?
Answer: B
The largest total is 10,000,000,000, above 2,147,483,647.
Q7/10 Three values of 1,000,000,000 are added in a 32-bit integer. What happens in Java?
Answer: C
Java integers wrap without an error. The sum is above 2,147,483,647.
Q8/10 The examples have five items, and the limits say n up to 200,000. How do you size the method?
Answer: B
The limits, not the examples, set the size.
Q9/10 The limits say the list may be empty. What should you do first?
Answer: B
An empty list is an edge case that the lower limit allows. max([]) in Python raises an error.
Q10/10 A task allows n up to 20 and asks for the best of all subsets. What do the limits tell you?
Answer: B
2 to the 20 is 1,048,576 steps, far under the budget.
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 | Cumulative build minutes | Platform | Easy | Read a limit that needs a 64-bit total |
| 2 | Longest green streak | Platform | Easy | Read n and choose a single pass |
| 3 | Largest gap between samples | Observe | Easy | Read n and choose sorting |
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.