Lesson 3.2
Count the steps
6 min · 7 steps
Step 1 of 7 · Explanation
One loop over
nitems takes aboutnsteps. Two nested loops over the same items take aboutn × nsteps. That's written O(n²).For 10 items the gap is small: 10 versus 100. For 100,000 items it's 100,000 versus 10,000,000,000. The bigger
ngets, the faster n² pulls away from n.Step 2 of 7 · Predict the result
What is
stepsat the end forn = 6?function solution(n) { let steps = 0 for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { steps++ } } return steps}3612216
Step 3 of 7 · Predict the result
Two loops, but not nested. What does it return for
n = 5?function solution(n) { let steps = 0 for (let i = 0; i < n; i++) steps++ for (let j = 0; j < n; j++) steps++ return steps}10255
Step 4 of 7 · Predict the result
A loop that halves. What does it return for
n = 64?function solution(n) { let steps = 0 while (n > 1) { n = Math.floor(n / 2) steps++ } return steps}63263
Step 5 of 7 · Pick the approach
n = 10⁵. You check every pair withj = i + 1, about 5 × 10⁹ checks. Assume a computer runs about 10⁸ simple steps per second, and the time limit is a few seconds.
What happens?- Too slow. About 50 seconds, so the test times out
- Fine, computers are very fast now
- Fine, because
j = i + 1already cuts the work
Step 6 of 7 · Pick the approach
Which one is O(n²)?
- A loop over
nums, withnums.includes(x)inside it - Two loops over
nums, one after the other - A
whileloop that halvesneach round - A loop over
numsthat readsnums[i - 1]
- A loop over
Step 7 of 7 · Recap
- Nested loops multiply, loops in sequence add.
- Halving each round is O(log n), very few steps.
- Watch for hidden loops like
includes,indexOfandsliceinside a loop. - A rough budget is about 10⁸ simple steps per second.