Lesson 1 · Unit 02
Accidental quadratics
Spot the loop hiding inside an innocent line
What you practise
- Membership tests on a list, building a string in a loop, a nested scan a dictionary would remove
- Counting operations before and after
Try a question from this lesson
Pick one
The list holds 10,000 different numbers. About how many comparisons does the membership test make in total?
def unique(items):
seen = []
for x in items:
if x not in seen:
seen.append(x)
return seenfunction unique(items) {
const seen = [];
for (const x of items) {
if (!seen.includes(x)) seen.push(x);
}
return seen;
}function unique(items: number[]) {
const seen: number[] = [];
for (const x of items) {
if (!seen.includes(x)) seen.push(x);
}
return seen;
}Hint
The test scans the items kept so far: none, then 1, then 2... What do those add up to?
Correct answer
About 50 million
Why
On a list, a membership test is a scan. With every item different it checks 0 + 1 + ... + 9,999 items: about 50 million comparisons. One loop on the page, two in the machine.
TypeScript noteAn empty [] gives TypeScript nothing to infer from, so seen is annotated as number[] by hand. The return type is then inferred from it.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The accidental quadratic
An accidental quadratic is a loop whose body hides a second loop.
The usual disguises: a membership test on a list, a search for a value, a count of how often something occurs, a copy of everything built so far.
Each reads like one step and costs up to n. Inside a loop over n items that makes n × n.
The question to ask of every line in a loop: does this take the same time when the data is ten times bigger?
9 more exercises in the app
- 2× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× order the lines
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.