Data Structures & AlgorithmsHardProduct-company MCQ pattern
What are the time complexities of versions P and Q?
What are the time complexities of versions 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; int x = Q(n/2); return x + x + n; }- A. P: O(log n), Q: O(log n)
- B. P: O(n log n), Q: O(log n)
- C. P: O(n), Q: O(log n)
- D. P: O(n), Q: O(n)
Correct answer: C. P: O(n), Q: O(log n)
P makes two recursive calls: T(n) = 2T(n/2) + O(1) = O(n) (2047 calls for n = 1024). Q calls itself once and reuses the result: T(n) = T(n/2) + O(1) = O(log n) (11 calls). Halving the argument alone does not make P logarithmic.
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
- What is the time complexity of solve(n)? python def solve(n): if n <= 0: return for i in range(n): pass # O(1) work solve(n - 1)
- How many of these statements are correct? (i) Dijkstra's algorithm with a binary heap runs in O((V + E) log V). (ii) Bellman–Ford runs in…
- Directed edges: A→B (2), A→C (5), C→B (−4), B→D (1). Dijkstra's algorithm, which finalises each vertex once when it is removed from the…
- DFS is run on a directed graph with edges A→B, A→C, B→D, C→D, C→A, D→B, E→C, E→D, starting from A, taking vertices and neighbours in…
- Kahn's algorithm is run on the DAG with edges 5→2, 5→0, 4→0, 4→1, 2→3, 3→1, always removing the SMALLEST-numbered vertex of in-degree 0 (a…
- How many topological orderings does the DAG with edges A→B, A→C, B→D, C→D, D→E, B→F have?