Counting work in loops
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most time-complexity questions boil down to counting how many times the innermost body of a loop runs. By learning four standard loop shapes, you can read the Big O of almost any iterative method in seconds.
Single loops
Time complexity is the number of basic steps an algorithm takes as a function of the input size n, written in Big O, such as O(n) for one loop over n items.
A single loop that walks from 0 to n - 1 by i++ runs n times. If the body inside the loop does a constant O(1) amount of work, the whole loop takes O(n) time.
Example 1 · Single loops with different step sizes are still O(n)
public class SingleLoopStepsDemo { public static void countSingleLoops(int n) { int stepByOne = 0; for (int i = 0; i < n; i++) { stepByOne++; }
int stepByTwo = 0; for (int i = 0; i < n; i += 2) { stepByTwo++; }
int stepByFive = 0; for (int i = 0; i < n; i += 5) { stepByFive++; }
System.out.println("n=" + n + " | i++: " + stepByOne + " | i+=2: " + stepByTwo + " | i+=5: " + stepByFive); }
public static void main(String[] args) { countSingleLoops(100); countSingleLoops(1000); }}n=100 | i++: 100 | i+=2: 50 | i+=5: 20 n=1000 | i++: 1000 | i+=2: 500 | i+=5: 200
What this code does
- When
ngrows 10× (from100to1000), all three counters grow 10× (100 -> 1000,50 -> 500,20 -> 200). - Because each counter grows in direct linear proportion to
n, all three loops areO(n).
for (int i = 0; i < n; i++)->nsteps ->O(n).for (int i = 0; i < n; i += 2)->n / 2steps ->O(n).for (int i = n - 1; i >= 0; i--)->nsteps backwards ->O(n).for (int i = 0; i < 100; i++)-> fixed100steps (does not depend onn) ->O(1).
What if the loop steps by 2 (i += 2) or by 10 (i += 10), or only walks up to n / 2? Then the loop runs n / 2 or n / 10 times. Because 1/2 and 1/10 are fixed constant multipliers, dropping constants still gives O(n)!
Predict the output
Count the loop steps
Read each loop and pick how many times the body runs.
Round 1 of 2
Nested loops
When one loop sits inside another loop, their iteration counts multiply. If the outer loop runs n times and the inner loop runs n times for every outer step, the inner body executes n * n = n^2 times, which is O(n²).
public class NestedCounts { public static void main(String[] args) { int n = 4, square = 0, fixed = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) square++; // runs n times per outer step for (int k = 0; k < 5; k++) fixed++; // runs 5 times per outer step } System.out.println("n * n = " + square); System.out.println("n * 5 = " + fixed); }}n * n = 16 n * 5 = 20
Be careful to check what the inner bound depends on: if the outer loop runs n times and the inner loop runs a fixed 5 times (for (int k = 0; k < 5; k++)), the total work is n * 5 = 5n, which is O(n), not O(n²)!
- Outer
0..n-1, inner0..n-1:n * n = n^2->O(n²). - Outer
0..n-1, inner0..m-1:n * m->O(n × m). - Outer
0..n-1, inner0..4(fixed constant5):5n->O(n). - Three nested loops each running
0..n-1:n * n * n = n^3->O(n³).
Dependent loops where j starts from i
When the inner loop starts at the outer counter, for (int j = i; j < n; j++), the inner body runs a different number of times on each pass. The code below counts them.
Write out the trip counts for each value of i: when i = 0, j runs n times; when i = 1, j runs n - 1 times; ... down to 1 time when i = n - 1. Adding those up gives the triangular sum: n + (n - 1) + ... + 2 + 1 = n(n + 1) / 2 = 0.5n^2 + 0.5n. Dropping the 0.5 multiplier and the 0.5n term still gives O(n²)!
Dependent loop for (j = i; j < n; j++), n = 5
Step 1 of 5
| Row | j=0 | j=1 | j=2 | j=3 | j=4 |
|---|---|---|---|---|---|
| i=0 | |||||
| i=1 | |||||
| i=2 | |||||
| i=3 | |||||
| i=4 |
- n
- 5
- steps
- 0
Example 2 · Dependent nested loop: why j = i still does O(n^2) work
public class DependentLoopDemo { public static void measureDependentLoop(int n) { int steps = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { steps++; } } int formula = n * (n + 1) / 2; System.out.println("n=" + n + " -> actual steps=" + steps + ", n(n+1)/2=" + formula); }
public static void main(String[] args) { measureDependentLoop(10); measureDependentLoop(100); }}n=10 -> actual steps=55, n(n+1)/2=55 n=100 -> actual steps=5050, n(n+1)/2=5050
What this code does
- Starting
jaticuts the work roughly in half compared toj = 0, givingn(n + 1) / 2steps. - When
nmultiplies by10(10 -> 100), the step count multiplies by roughly100(55 -> 5050), confirmingO(n²)growth.
In many pair and subarray problems, the inner loop counter j depends on the outer loop counter i, such as for (int j = i; j < n; j++) or for (int j = 0; j < i; j++). How many times does the inner body run now?
- i = 0: inner loop
j = 0..n-1runsntimes. - i = 1: inner loop
j = 1..n-1runsn - 1times. - i = n - 1: inner loop
j = n-1..n-1runs1time. - Total =
1 + 2 + ... + n = n(n + 1) / 2, which isO(n^2).
j runs 0..i or i..n-1 or i+1..n-1, the average inner trip count is roughly n / 2, so n * (n / 2) is always O(n^2).Loops one after another versus nested
Beginners sometimes see two for loops in a method and immediately guess O(n²). Always check the curly braces {} to see whether the second loop is inside the first loop or after the first loop.
Example 3 · Sequential loops (add) versus nested loops (multiply)
public class SequentialVsNestedDemo { // Two sequential loops: n + n = 2n steps -> O(n) public static int sequentialLoops(int n) { int steps = 0; for (int i = 0; i < n; i++) { steps++; } for (int j = 0; j < n; j++) { steps++; } return steps; }
// Two nested loops: n * n = n^2 steps -> O(n^2) public static int nestedLoops(int n) { int steps = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { steps++; } } return steps; }
public static void main(String[] args) { System.out.println("n=50 sequential: " + sequentialLoops(50)); System.out.println("n=50 nested : " + nestedLoops(50)); }}n=50 sequential: 100 n=50 nested : 2500
What this code does
- In
sequentialLoops, the first loop finishes completely before the second loop starts, so the total is50 + 50 = 100. - In
nestedLoops, the inner loop runs a full50times on each of the50outer iterations, giving50 * 50 = 2500.
- Loop A (
nsteps) followed by Loop B (nsteps):n + n = 2n->O(n). - Loop A (
nsteps) followed by Loop B (msteps):n + m->O(n + m). - Loop A (
nsteps) followed by a nested pair loop (n^2steps):n + n^2->O(n²)(the bigger term wins).
Sequential loops (one after another) add their step counts: a loop of n steps followed by another loop of n steps does n + n = 2n steps, which is O(n). Nested loops (one inside another) multiply their step counts: n * n = n^2 (O(n²)).
Next step
Check your understanding
10 quick questions