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; }- A. P: O(n log n), Q: O(n)
- B. P: O(n), Q: O(n)
- C. P: O(n), Q: O(n log n)
- 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.
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
- A directed graph has edges E→A, D→A, D→E, B→D, D→C. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does…
- Keys 49, 39, 29 are inserted in this order into an empty AVL tree. After AVL rebalancing (a single rotation resolves the imbalance here)…
- An undirected connected graph has edges A–B, B–C, C–D, D–E, E–F, F–G, G–H, C–G, A–C. How many articulation points (cut vertices) and how…
- What are the time complexities of P and Q? c int P(int n) { if (n <= 1) return 1; return P(n/2) + P(n/2) + P(n/2) + P(n/2) + n; } int…
- A trie is built from the words {den, dog, car, card, do, cat, deer}. Using the trie (walk the prefix's characters, then count all words in…
- Build a binary min-heap in place from the array [32, 59, 35, 72, 53, 57, 16, 42, 15] using bottom-up heapify (sift-down from the last…