ProgrammingVery hardGoldman Sachs OA · Amazon OA

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 / 2) + f(n / 2)
End Function
  1. A. O(log n)
  2. B. O(n log n)
  3. C. O(2ⁿ)
  4. D. O(n)

Correct answer: D. O(n)

T(n) = 2T(n/2) + O(1). The call tree has log₂ n levels but doubles in width each time, ending with about n leaves, so there are about 2n calls: O(n). Computing f(n / 2) once and doubling it would make it O(log n).

More Pseudocode and Code Tracing questions

Exams that ask this topic