Data Structures & AlgorithmsHardAmazon/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 P(n/2) + P(n/2) + P(n/2) + P(n/2) + n; }
int Q(int n) { if (n <= 1) return 1; return Q(n/2) + Q(n/2); }
  1. A. P: O(n²), Q: O(n²)
  2. B. P: O(n²), Q: O(n)
  3. C. P: O(n), Q: O(n²)
  4. D. P: O(log n), Q: O(log n)

Correct answer: B. P: O(n²), Q: O(n)

P makes four recursive calls on n/2, plus O(n) work (recurrence T(n) = 4T(n/2) + O(n)), giving O(n²). Q makes two recursive calls on n/2, plus O(1) work (T(n) = 2T(n/2) + O(1)), giving O(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