Dependent nested loop (j from i to n): time complexity step by step
An inner loop that starts at i: Σ (n − i + 1) = n(n+1)/2 iterations. The full count and why it is still Θ(n²).
The question
Consider the algorithm below, where n is the input size. Algorithm Triangle (n) count <— 0 FOR i <— 1 to n DO FOR j <— i 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
This time the inner loop starts at j <— i, so it gets shorter as i grows: n iterations, then n-1, then n-2, … down to 1.
count <— 0: one assignment.
The outer loop starts once: i <— 1.
The outer test i ≤ n runs n times plus one exit check: n+1 times.
After each outer iteration, the FOR moves i on: n times.
The inner loop starts once for every i: n times.
For a given i, j runs from i to n: that is n - i + 1 iterations (the rule n − m + 1). Over all i: sum from i=1 to n of (n − i + 1) = n + (n−1) + … + 1 = n(n+1)/2.
Each inner loop also has its one extra exit test, once per i: the inner tests are n(n+1)/2 + n.
count + 1 runs once per inner iteration: n(n+1)/2 times.
RETURN count runs once.
Add the column: three lots of n(n+1)/2, plus 1 + 1 + (n+1) + n + n + n + 1. That is (3n^2 + 11n + 8)/2. 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.