Nested loop time complexity with summations, step by step

Count a loop inside a loop with summations: n(n+1) inner tests, n² iterations, total 3n² + 4n + 4 ∈ Θ(n²).

The question

Consider the algorithm below, where n is the input size. Algorithm Pairs (n) count <— 0 FOR i <— 1 to n DO FOR j <— 1 to n DO count <— count + 1 END FOR END FOR RETURN count END Part 1: Find the worst-case time complexity (Big O). Part 2: Find the best-case time complexity (Big Ω). Part 3: Find Big Θ.

Worked solution

A loop inside a loop. The inner loop runs completely for every value of i. There is no early exit, so worst and best do the same work. Let's count it.

count <— 0: one assignment.

The outer loop starts once: i <— 1.

The outer test i ≤ n runs for i = 1 … n (n times), plus one extra check to exit: n+1 times.

After each outer iteration, the FOR moves i on: n times.

Each time the outer loop runs, the inner loop starts again: j <— 1 happens n times in total.

For each i the inner test runs n+1 times. Over all i: sum from i=1 to n of (n+1) = n(n+1). Adding instead of multiplying is the usual mistake here, so keep it as a sum over i.

The inner FOR moves j on n times for each i: sum from i=1 to n of n = n·n = n^2.

count + 1 runs once per inner iteration: n^2 times.

RETURN count runs once.

Add the column: 1 + 1 + (n+1) + n + n + (n^2 + n) + n^2 + n^2 + 1 = 3n^2 + 4n + 4. The fastest-growing term is n^2: ∈ O(n^2).

The rest

Next: the best case (Big Ω) and Big Θ, step by step, with a free account.