Back to the 2025 paper

Module 1: Introduction

20257m

Define time complexity and space complexity. Write an algorithm for adding n natural numbers and find the space required by that algorithm.

Worked SolutionAI Assisted

Time and Space Complexity + Algorithm to Add nn Naturals

Definitions

  • Time Complexity: asymptotic number of basic operations (steps) as function of input size nn, T(n)T(n).
  • Space Complexity: asymptotic total memory (input + auxiliary + recursion stack) S(n)S(n); often reported as auxiliary space (extra beyond input).

Algorithm — Sum of First nn Natural Numbers

Iterative O(n)O(n) time, O(1)O(1) aux space:

Algorithm SumNatural(n):
  sum ← 0
  for i ← 1 to n:
    sum ← sum + i
  return sum

Time: nn iterations × O(1)O(1) → T(n)=Θ(n)T(n)=\Theta(n) (nn additions). Space: variables sumsum, ii, nn → 3 words → S(n)=Θ(1)S(n)=\Theta(1) auxiliary (Θ(n)\Theta(n) if counting input array? Here input is just nn → O(1)O(1)).

Formula O(1)O(1) time (mathematical):

Algorithm SumFormula(n):
  return n*(n+1)//2

Time Θ(1)\Theta(1) arithmetic operations, space Θ(1)\Theta(1). Uses closed form ∑i=1ni=n(n+1)/2\sum_{i=1}^n i = n(n+1)/2.

Recursive (for illustration):

RecSum(n): if n==1 return 1 else return n + RecSum(n-1)

Time Θ(n)\Theta(n), stack space Θ(n)\Theta(n) due to nn frames — worse.

Analysis Summary

Variant Time Auxiliary Space Total Space
Iterative loop Θ(n)\Theta(n) O(1)O(1) O(1)O(1)
Formula Θ(1)\Theta(1) O(1)O(1) O(1)O(1)
Recursive Θ(n)\Theta(n) Θ(n)\Theta(n) stack Θ(n)\Theta(n)

Best practical: formula O(1)O(1). If required to demonstrate space complexity concept, loop shows O(1)O(1) auxiliary despite O(n)O(n) time.

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.