Lesson 2 · Unit 01
Loops inside loops
Nested loops multiply: quadratic time
What you practise
- O(n²)
- Nested multiplies, sequential adds
- Drop constants and smaller terms
- Pairs
i < j
Try a question from this lesson
Pick one
A loop inside a loop over the same list takes 1 second for 1,000 items. Roughly how long for 2,000 items?
Hint
Quadratic work does not simply double when n doubles. What happens to n × n?
Correct answer
4 seconds
Why
Quadratic work grows with n × n, so doubling n multiplies it by 2 × 2 = 4. Two seconds would be linear growth.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Nested loops multiply
A loop inside a loop over the same n items runs its body n × n times. That is O(n²), quadratic time.
Double n and the work goes up four times. Ten times the input means a hundred times the work.
def all_pairs(names):
for a in names:
for b in names:
print(a, b) # n * n timesfunction allPairs(names) {
for (const a of names) {
for (const b of names) {
console.log(a, b); // n * n times
}
}
}function allPairs(names: string[]): void {
for (const a of names) {
for (const b of names) {
console.log(a, b); // n * n times
}
}
}TypeScript note: void is the return type of a function that returns nothing. It only does something: here, printing.
Concept
Keep only the biggest term
Big-O keeps what matters when n is huge.
Drop constants: 3n steps is O(n). Drop smaller terms: n² + n steps is O(n²), because at n = 1,000 the n² part is a million and the n part is a rounding error.
10 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× match the pairs
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.