ProgrammingHardAmazon OA · Goldman Sachs 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?
Procedure f(Integer n)
    if (n <= 1)
        return
    end if
    for (each i from 1 to n)
        work()          // O(1)
    end for
    f(n / 2)
    f(n / 2)
End Procedure
  1. A. O(n)
  2. B. O(n²)
  3. C. O(n log n)
  4. D. O(log n)

Correct answer: C. O(n log n)

T(n) = 2T(n/2) + n. Each level of the recursion does n units of work in total, and there are log₂ n levels, so O(n log n) — the same shape as merge sort.

More Pseudocode and Code Tracing questions

Exams that ask this topic