Data Structures & AlgorithmsHardProduct-company placement
How many calls of g (including the first) are made when g(7) is evaluated, and what value is returned?
How many calls of g (including the first) are made when g(7) is evaluated, and what value is returned?
int g(int n) {
if (n <= 2) return n;
return g(n - 1) + g(n - 2) + g(n - 3);
}- A. 8 calls, returns 37
- B. 46 calls, returns 38
- C. 41 calls, returns 37
- D. 46 calls, returns 37
Correct answer: D. 46 calls, returns 37
calls(n) = 1 + calls(n−1) + calls(n−2) + calls(n−3) with calls = 1 for n ≤ 2 (and n = 0, 1, 2 return 0, 1, 2), giving 46 calls and value 37. With memoisation only 8 distinct calls would compute.
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
- The words trie, tried, trip, try, tree are inserted into an empty trie (one node per character, shared prefixes share nodes, plus a root)…
- In the grid 21112 / 11110 / 10111 / 11111 (rows top to bottom; 2 = rotten, 1 = fresh, 0 = empty), every minute each rotten orange rots its…
- An undirected graph has edges A–E, A–H, B–F, C–E, C–G, D–G, D–H, E–F, E–G, F–H. BFS starts at A and always scans neighbours in…
- A tree on vertices 1–10 has edges 2–1, 3–2, 4–1, 5–4, 6–1, 7–3, 8–7, 9–5, 10–9. What is the size of a minimum DOMINATING set (every vertex…
- What is the length of the longest common subsequence of CONTEST and RECESSION, and how many DISTINCT longest common subsequences (as…
- A tree on vertices 1–8 has edges 2–1, 3–2, 4–1, 5–2, 6–5, 7–2, 8–1. What is the sum of the distances (in edges) over all unordered pairs…