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 P(n/2) + P(n/2); }
int Q(int n) { if (n <= 1) return 1; return Q(n/2) + Q(n/2) + Q(n/2) + Q(n/2) + n; }- A. P: O(log n), Q: O(log n)
- B. P: O(n), Q: O(n²)
- C. P: O(n²), Q: O(n)
- D. P: O(n), Q: O(n)
Correct answer: B. P: O(n), Q: O(n²)
P makes two recursive calls on n/2, plus O(1) work (recurrence T(n) = 2T(n/2) + O(1)), giving O(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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Keys 30, 11, 59, 70, 43, 35 are inserted via separate chaining (h(k) = k mod 8, new keys appended to the end of the chain) into a table of…
- Undirected graph edges: A–C, A–D, D–C, C–B. Using a BFS 2-colouring, is this graph bipartite?
- 0/1 knapsack, capacity 11. Items (weight, value): (4, 6), (1, 7), (6, 3), (2, 2). What is the maximum total value?
- Keys 92, 78, 40, 55, 53, 90, 42 are inserted via separate chaining (h(k) = k mod 5, new keys appended to the end of the chain) into a…
- A binary tree has preorder traversal [53, 5, 2, 10, 30, 72, 65, 60] and inorder traversal [2, 5, 10, 30, 53, 60, 65, 72]. Reconstructing…
- A directed graph has edges E→C, B→E, A→E, C→A, B→C, A→D, E→D. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a…