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);
}
  1. A. 63 moves, 127 calls
  2. B. 127 moves, 255 calls
  3. C. 64 moves, 127 calls
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic