Video in progress
What is the time complexity of the following method?
static int count(int n) {
int c = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < n; j *= 2) {
c++;
}
}
return c;
}
O(n log n). The outer loop runs n times, and the inner one runs about log₂n times, because it doubles j each time. They don't depend on each other, so you multiply.
📖 Answer
When you see nested loops, don't say O(n²) by reflex; look at each loop's step.
The inner loop: j goes 1, 2, 4, 8, ... and stops when it reaches n. How many steps? Until 2ᵏ ≥ n, so k ≈ log₂n. This doesn't depend on i.
The outer loop runs n times. Total: n · log n.
It's easy to check: at n = 1024 the inner loop runs 10 times and count returns 10,240. With n² it would have been a million.
Similar traps:
for (j = i; j < n; j++): the inner loop gets shorter, but the total is n(n-1)/2, still O(n²);while (n > 0) n /= 2;is O(log n);- two loops in sequence (not nested) add up: O(n) + O(n) = O(n).
Sign up to mark studied questions and save your progress.