Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

What are the time complexities of P and Q?

What are the time complexities of P and Q?
int P(int n) { if (n <= 1) return 1; return return P(n/2) + n; }
int Q(int n) { if (n <= 1) return 1; return Q(n/2) + Q(n/2) + n; }
  1. A. P: O(n log n), Q: O(n)
  2. B. P: O(n), Q: O(n)
  3. C. P: O(n), Q: O(n log n)
  4. D. P: O(log n), Q: O(log n)

Correct answer: C. P: O(n), Q: O(n log n)

P makes one recursive call on n/2, plus O(n) work (recurrence T(n) = 1T(n/2) + O(n)), giving O(n). Q makes two recursive calls on n/2, plus O(n) work (T(n) = 2T(n/2) + O(n)), giving O(n log n). The number of recursive calls at each level, not just the depth, decides the final complexity.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic