The Plain Picture#
Working out a travel time: steps done one after another add up ("30 min to the station + 2 hours on the train"); a step done for every item in a list multiplies ("5 minutes at each of 12 shops").
The Real Names and Rules#
Rule 1 — Sequential blocks add, then keep the biggest.
for (int i = 0; i < n; i++) { ... } // O(n)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) { ... } // O(n²)
// total O(n + n²) = O(n²)Rule 2 — Nested loops multiply.
for (
int i = 0;
i < n;
i++ // n times
) for (
int j = 0;
j < m;
j++ // × m times
) work(); // O(n · m)Rule 3 — A loop whose inner range depends on the outer one: add up the actual counts.
for (int i = 0; i < n; i++) for (
int j = i + 1;
j < n;
j++ // the pairs loop from 01_java_basics.md Ch 6
) work();The inner loop runs n−1, then n−2, …, 1, 0 times. Total = n(n−1)/2 ≈ n²/2 → O(n²). Measured:
pairs loop n=1000: 499500 (n^2/2 = 500000)Rule 4 — Halving (or doubling) loops are O(log n) (Ch 3).
while (n > 1) { n /= 2; } // O(log n)
for (int i = 1; i < n; i *= 2) { ... } // O(log n)Rule 5 — A loop of n rounds with an O(log n) body is O(n log n).
for (int i = 0; i < n; i++) for (
int j = 1;
j < n;
j *= 2 // log n
) work(); // O(n log n)Rule 6 — Different inputs get different letters. Don't call everything n.
for (String a : listA) // size a
for (String b : listB) // size b
compare(a, b); // O(a · b) — NOT O(n²)Rule 7 — Count the cost of every call inside the loop. A method call is not one step if the method itself loops:
for (int i = 0; i < n; i++) {
if (list.contains(x)) { ... } // contains on a List scans it: O(n) → whole loop O(n²)
s = s + "x"; // String concatenation copies: O(length) → O(n²) (02_java_classes_objects_and_memory.md Ch 7)
sub = s.substring(0, i); // substring copies i characters: O(i) → O(n²)
}These hidden loops are the #1 reason "O(n)" interview solutions are actually O(n²). Chapter 9 lists the costs.
Rule 8 — Early exits don't change the worst case. hasDuplicateSlow returns as soon as it finds a duplicate — but with no duplicates it
checks every pair, so it's still O(n²) in the worst case (Ch 5).
Worked example — the three duplicate checkers from Part 0#
// A: check every pair O(n²) time, O(1) extra space
for (int i = 0; i < a.length; i++) for (int j = i + 1; j < a.length; j++) if (
a[i] == a[j]
) return true;
// B: sort a copy, then compare neighbours O(n log n) time (the sort dominates), O(n) space (the copy)
int[] b = a.clone(); // O(n)
Arrays.sort(b); // O(n log n)
for (
int i = 1;
i < b.length;
i++ // O(n)
) if (b[i] == b[i - 1]) return true;
// C: remember what you've seen O(n) time on average, O(n) space
Set<Integer> seen = new HashSet<>();
for (int x : a) if (!seen.add(x)) return true; // add is O(1) on average (07_java_collections_internals.md)This time vs space trade-off — spend memory (a set) to save time — is the single most common optimisation in interviews.
Check yourself
0 questionsGive the time complexity of each:
// (a)
for (int i = 0; i < n; i++) {}
for (int j = 0; j < n; j++) {}
// (b)
for (int i = 0; i < n; i++) for (int j = 0; j < 10; j++) {}
// (c)
for (int i = 0; i < n; i++) for (int j = i; j < n; j++) {}
// (d)
for (int i = n; i > 0; i /= 2) for (int j = 0; j < n; j++) {}
// (e)
for (String w : words) {
if (dictionaryList.contains(w)) count++;
} // words: w items, dictionaryList: d itemsAnswers:
(a) O(n) — O(n) + O(n).
(b) O(n) — the inner loop is a constant 10.
(c) O(n²) — about n²/2.
(d) O(n log n) — log n outer rounds × n inner.
(e) O(w · d) —
List.containsscans the list. Using aHashSetfor the dictionary makes it O(w + d).