ProgrammingModerateTCS NQT · Accenture

What is the time complexity of the following pseudocode, as a function of n?

What is the time complexity of the following pseudocode, as a function of n?
Function f(Integer n)
    if (n <= 1)
        return 1
    end if
    return f(n - 1) + f(n - 1)
End Function
  1. A. O(2ⁿ)
  2. B. O(n)
  3. C. O(n²)
  4. D. O(n log n)

Correct answer: A. O(2ⁿ)

Each call makes two calls on n − 1, so the call tree doubles at every level: 1 + 2 + 4 + … + 2ⁿ⁻¹ calls, i.e. O(2ⁿ). Writing 2 * f(n − 1) instead would make it O(n).

More Pseudocode and Code Tracing questions

Exams that ask this topic