Data Structures & AlgorithmsModerateProduct-company MCQ pattern
For n = 6, how many disk moves does this Tower of Hanoi function count, and how many calls of hanoi are made in total?
For n = 6, how many disk moves does this Tower of Hanoi function count, and how many calls of hanoi are made in total?
int hanoi(int n, char a, char b, char c) {
if (n == 0) return 0;
return hanoi(n - 1, a, c, b) + 1 + hanoi(n - 1, c, b, a);
}- A. 63 moves, 127 calls
- B. 127 moves, 255 calls
- C. 64 moves, 127 calls
- D. 63 moves, 63 calls
Correct answer: A. 63 moves, 127 calls
Moves M(n) = 2M(n − 1) + 1 = 2⁶ − 1 = 63. Calls K(n) = 2K(n − 1) + 1 with K(0) = 1 (the base case is also a call), so K(6) = 2⁷ − 1 = 127. Counting only the calls that move a disk gives 63.
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 robot moves only right or down on a 3 × 4 grid of cells (3 rows, 4 columns) from the top-left cell to the bottom-right cell. The cell in…
- What is the length of the longest palindromic SUBSEQUENCE of CHARACTER?
- Coins of 1, 5, 6 and 8 are available in unlimited supply. For amount 11, how many coins does the 'largest coin first' greedy method use…
- Each job takes 1 unit of time; only one job runs at a time. Jobs (deadline, profit): J1 (2, 100), J2 (1, 19), J3 (2, 27), J4 (1, 25), J5…
- Characters a, b, c, d, e occur 4, 7, 9, 12 and 20 times. With an optimal Huffman code, how many bits are needed to encode the whole text?
- Bellman–Ford from A relaxes the directed edges in the fixed order C→D (2), B→C (3), A→B (4), A→C (9), B→D (7). After the FIRST full pass…