Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move.
Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move.
moves = []
def hanoi(n, a, b, c):
if n == 0: return
hanoi(n - 1, a, c, b)
moves.append((a, c))
hanoi(n - 1, b, a, c)
hanoi(4, "A", "B", "C")
print(len(moves), moves[0], moves[7])What is printed?- A. 15 ('A', 'B') ('A', 'C')
- B. 15 ('A', 'B') ('B', 'C')
- C. 16 ('A', 'B') ('A', 'C')
- D. 15 ('A', 'C') ('A', 'C')
Correct answer: A. 15 ('A', 'B') ('A', 'C')
T(n) = 2T(n − 1) + 1 = 2ⁿ − 1 = 15 moves for 4 disks. With an even number of disks the first move goes A → B (the smallest disk heads for the spare peg). Move index 7 is the middle move – the largest disk going A → C – after the top 3 disks (7 moves) are parked on B. O(2ⁿ).
More Coding Interview Problems questions
- Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by…
- Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth). python def…
- Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1). python…
- Problem: Trace the output of a recursive function that prints before and after its recursive call. python def walk(n): if n == 0: return…
- Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by…
- Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a…