ProgrammingVery hardGoldman Sachs OA · TCS Digital

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

Correct answer: C. O(n²)

T(n) = 4T(n/2) + n. Level k of the recursion has 4ᵏ calls each doing n/2ᵏ work, i.e. 2ᵏ n in total; the last level dominates with about n² work (log₂ 4 = 2 > 1). So O(n²).

More Pseudocode and Code Tracing questions

Exams that ask this topic