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

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

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