← TCS bank

TCS · Question 2

Tower of Hanoi Problem

C++code⏱ O(2ⁿ)💾 O(n)
Service-based

Problem

Move n disks from source to destination using an auxiliary rod, following the rules.

Approach

Move n-1 aside, shift the largest, then move n-1 again.

Time O(2ⁿ)Space O(n)

How it works

  1. 1Move n-1 disks to the auxiliary rod.
  2. 2Move the largest disk to the destination.
  3. 3Move the n-1 stack on top of it.

Sample input / output

Input:
n = 2, rods = A (src), B (aux), C (dst)
Output:
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C

Constraints

1 <= n <= 20; 2^n - 1 moves.

Solution — read it, then walk it

Time O(2ⁿ)Space O(n)Branches 1Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesnoSTARTinclude <iostream>using namespace stdDEFINE hanoi(int n, charsrc, char aux, char dst)if (n == 1)cout << "Move disk 1 from "<< src << " to " << dst <<endlRETURNhanoi(n - 1, src, dst, aux)cout << "Move disk " << n<< " from " << src << " to" << dst << endlhanoi(n - 1, aux, src, dst)DEFINE main()hanoi(2, 'A', 'B', 'C')RETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/13

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits