Skip to lesson

Counting work in loops

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)

SingleLoopStepsDemo.javaJava
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);    }}
Output
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 n grows 10× (from 100 to 1000), all three counters grow 10× (100 -> 1000, 50 -> 500, 20 -> 200).
  • Because each counter grows in direct linear proportion to n, all three loops are O(n).
  • for (int i = 0; i < n; i++) -> n steps -> O(n).
  • for (int i = 0; i < n; i += 2) -> n / 2 steps -> O(n).
  • for (int i = n - 1; i >= 0; i--) -> n steps backwards -> O(n).
  • for (int i = 0; i < 100; i++) -> fixed 100 steps (does not depend on n) -> 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

int n = 12;
int count = 0;
for (int i = 0; i < n; i += 3) {
count++;
}
System.out.println(count);

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²).

NestedCounts.javaJava
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);    }}
Output
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, inner 0..n-1: n * n = n^2 -> O(n²).
  • Outer 0..n-1, inner 0..m-1: n * m -> O(n × m).
  • Outer 0..n-1, inner 0..4 (fixed constant 5): 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

Rowj=0j=1j=2j=3j=4
i=0
i=1
i=2
i=3
i=4
n
5
steps
0
Each cell is one run of the inner body. The number inside is the running count of steps. Nothing has run yet.

Example 2 · Dependent nested loop: why j = i still does O(n^2) work

DependentLoopDemo.javaJava
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);    }}
Output
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 j at i cuts the work roughly in half compared to j = 0, giving n(n + 1) / 2 steps.
  • When n multiplies by 10 (10 -> 100), the step count multiplies by roughly 100 (55 -> 5050), confirming O(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?

  1. i = 0: inner loop j = 0..n-1 runs n times.
  2. i = 1: inner loop j = 1..n-1 runs n - 1 times.
  3. i = n - 1: inner loop j = n-1..n-1 runs 1 time.
  4. Total = 1 + 2 + ... + n = n(n + 1) / 2, which is O(n^2).
Whether 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)

SequentialVsNestedDemo.javaJava
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));    }}
Output
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 is 50 + 50 = 100.
  • In nestedLoops, the inner loop runs a full 50 times on each of the 50 outer iterations, giving 50 * 50 = 2500.
  • Loop A (n steps) followed by Loop B (n steps): n + n = 2n -> O(n).
  • Loop A (n steps) followed by Loop B (m steps): n + m -> O(n + m).
  • Loop A (n steps) followed by a nested pair loop (n^2 steps): 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