Data Structures & AlgorithmsHardProduct-company MCQ pattern
What is the time complexity of solve(n)?
What is the time complexity of solve(n)?
def solve(n):
if n <= 0:
return
for i in range(n):
pass # O(1) work
solve(n - 1)- A. O(2ⁿ)
- B. O(n)
- C. O(n log n)
- D. O(n²)
Correct answer: D. O(n²)
T(n) = T(n − 1) + n, so the loop runs n + (n − 1) + … + 1 = n(n + 1)/2 times (5050 for n = 100): O(n²). O(n) counts only the recursion depth, and O(2ⁿ) would need two recursive calls.
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
- 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?
- Prim's algorithm starts at A on the undirected graph with edges A–B (3), A–C (1), B–C (7), B–D (5), C–D (2), C–E (7), D–E (3), D–F (8)…