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); }- A. P: O(n²), Q: O(n²)
- B. P: O(n²), Q: O(n)
- C. P: O(n), Q: O(n²)
- 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.
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 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…
- Keys 47, 33, 29, 18, 55, 67 are inserted via separate chaining (h(k) = k mod 7, new keys appended to the end of the chain) into a table of…
- Undirected graph edges: A–B, C–B, A–D, D–B, C–D, C–A. Using a BFS 2-colouring, is this graph bipartite?
- A disjoint-set (union-find with union by rank and path compression) over 9 elements (0 to 8), each initially its own component, runs this…
- Directed edges: A→B (5), A→C (6), C→B (-3), B→D (1). Dijkstra's algorithm, which finalises each vertex once when it is removed from the…