Lesson 3 of 9
Time Complexity — loops
0 of 9 lessons done
Lesson notes
Most complexity questions in placement tests are really questions about loops. Learn to read a loop’s growth pattern and 80% of the marks are yours.
The core patterns
for (i = 0; i < n; i++)— runsntimes → O(n).- Two independent nested loops over
n→n × niterations → O(n²). - Dependent bound:
for (i = 0; i < n; i++) for (j = 0; j <= i; j++)— inner loop runs1 + 2 + … + n = n(n+1)/2times → still O(n²), but exam options often bait you with O(n log n) here. - Multiplicative update:
for (i = 1; i < n; i = i * 2)—idoubles each pass, so the loop runslog₂ ntimes → O(log n). The same holds fori = i / 2. - Combined: an O(n) loop containing an O(log n) loop → O(n log n) — the shape of heap sort and merge sort.
The method (works on any loop)
- Write the number of iterations of each loop as a function of
n. - Multiply counts for nested loops; add counts for sequential loops.
- Keep the fastest-growing term and drop constant factors:
3n² + 5n + 7is O(n²).
Traps to watch
- An early
break/returnchanges the best case, not the worst case — read which case the question asks for. i = i * 2starting from 0 never progresses — a definiteness trap.- Loop bounds like
i * i < nmeaniruns to√n→ O(√n).
Work the examples in the video by hand before checking — the counting habit is the skill.