Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
What does fun(3) print?
What does fun(3) print?
void fun(int n) {
if (n > 0) {
fun(n - 1);
printf("%d ", n);
fun(n - 1);
}
}- A. 3 2 1 1 2 1 1
- B. 1 2 1 3 1 2 1
- C. 1 2 3 1 2 1
- D. 3 2 1 2 1
Correct answer: B. 1 2 1 3 1 2 1
fun(1) prints 1; fun(2) prints fun(1), 2, fun(1) = 1 2 1; fun(3) prints 1 2 1, 3, 1 2 1. In general 2ⁿ − 1 numbers are printed, the same pattern as Tower of Hanoi moves.
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 are the time complexities of versions P and Q? c int P(int n) { if (n <= 1) return 1; return P(n/2) + P(n/2) + n; } int Q(int n) { if…
- 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…