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; }- A. P: O(log n), Q: O(log n)
- B. P: O(n log n), Q: O(n log n)
- C. P: O(n²), Q: O(n log n)
- 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.
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
- Undirected graph edges: E–D, E–C, A–C, D–C, B–A, B–E, B–D. Using a BFS 2-colouring, is this graph bipartite?
- Keys 69, 79, 89 are inserted in this order into an empty AVL tree. After AVL rebalancing (a single rotation resolves the imbalance here)…
- Keys 4, 74, 93, 84, 37, 87, 63 are inserted via separate chaining (h(k) = k mod 7, new keys appended to the end of the chain) into a table…
- Keys 79, 74, 70, 89, 2, 6, 8 are inserted via separate chaining (h(k) = k mod 7, new keys appended to the end of the chain) into a table…
- Keys 75, 53, 77, 17, 31, 29, 21, 5, 95 are inserted in this order into an empty BST (no rebalancing). What is the height of the tree…
- Directed edges: A→B (4), A→C (5), C→B (-4), B→D (1). Dijkstra's algorithm, which finalises each vertex once when it is removed from the…