🗼 Tower of Hanoi - Code Comparison

Interactive Step-by-Step Analysis & Execution

📝 Code 1 (Your Solution 5)

public class Solution { public static void towerOfHanoi(int n, String src, String helper, String dest) { if(n == 1) { System.out.println("transfer disk " + n + " from " + src + " to " + dest); return; } // Transfer top n-1 from src to helper using dest towerOfHanoi(n-1, src, dest, helper); // Transfer nth from src to dest System.out.println("transfer disk " + n + " from " + src + " to " + helper); // Transfer n-1 from helper to dest using src towerOfHanoi(n-1, helper, src, dest); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter number of disks: "); int n = sc.nextInt(); towerOfHanoi(n, "A", "B", "C"); } }

⚡ Code 2 (Optimized Version)

public class TowerOfHanoi { static int steps = 0; // total steps tracker static void solveHanoi(int n, char source, char helper, char destination) { if (n == 1) { steps++; System.out.println("Move disk 1 from " + source + " to " + destination); return; } // Step 1: Move n-1 disks from source to helper solveHanoi(n - 1, source, destination, helper); // Step 2: Move nth disk from source to destination steps++; System.out.println("Move disk " + n + " from " + source + " to " + destination); // Step 3: Move n-1 disks from helper to destination solveHanoi(n - 1, helper, source, destination); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter number of disks: "); int n = sc.nextInt(); steps = 0; // Reset counter solveHanoi(n, 'A', 'B', 'C'); System.out.println("Total steps = " + steps); } }

🔍 Optimization Analysis

🏆 Winner: Code 2 (Optimized Version)

✅ Code 2 Advantages

  • Memory Efficient: Uses char (2 bytes) vs String objects
  • Performance: Faster char operations
  • Step Counting: Tracks total moves
  • Less Garbage Collection: No string concatenation overhead
  • Correct Logic: Proper disk movement sequence

❌ Code 1 Issues

  • Memory Overhead: String objects on heap
  • Logic Error: Prints wrong destination in middle step
  • No Step Count: Missing useful information
  • String Operations: Slower than char operations
  • Less Readable: Longer parameter names

🎮 Interactive Step-by-Step Execution

⚠️ Max (2^n-1)Steps...
Tower A
Tower B
Tower C
Ready for execution... Click a button above!