Time complexity of summing an array: Big O, Big Ω and Big Θ, step by step
Count every operation of a loop that sums an array: the loop start, the n+1 tests, the increments and the additions, then find Big O, Big Ω and Big Θ.
The question
Consider the algorithm below, where n is the input size. Algorithm Sum (A, n) total <— 0 FOR i <— 0 to n-1 DO total <— total + A[i] END FOR RETURN total 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
Big O is the worst case, the most work. This loop has no early exit: it always visits all n elements, so we count everything it does.
total <— 0 is one assignment: 1 time.
The loop starts once: i <— 0.
The test i ≤ n-1 runs for i = 0 … n-1 (n times), plus one extra check to exit: n+1 times.
Each iteration adds one element. One + per iteration: n times.
After each iteration, the FOR moves i to the next value: n increments.
RETURN total runs once.
Add the column: 1 + 1 + (n+1) + n + n + 1 = 3n + 4. Keep the fastest-growing term: 3n + 4 ∈ O(n).
The rest
Next: the best case (Big Ω) and Big Θ, step by step, with a free account.