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

Correct answer: B. O(n log n)

T(n) = T(n/3) + T(2n/3) + n. Every level of the recursion tree does at most n work in total, and the longest branch (shrinking by 2/3) has about log₃/₂ n levels, so T(n) = O(n log n).

More Pseudocode and Code Tracing questions

Exams that ask this topic