1. Bitwise / Gray Code Mathematical Generation
Intuition
For any move k (from 1 to 2N - 1), the disk to move is the 1-based index of the lowest set bit of k (__builtin_ctz(k) + 1). Even-sized and odd-sized disks alternate directions in a cyclic manner.
When to apply: When you want to compute individual move transitions in O(1) time without recursion.
Algorithm
- Calculate total moves = 2N - 1.
- For step k from 1 to 2N - 1:
- - Disk index = (k & -k) index.
- - Move disk between source and destination following parity direction rules.
- Return total moves count.
#include <iostream>#include <cmath> using namespace std; class Solution {public: long long tohBitwise(int n, int from, int to, int aux) { long long totalMoves = (1LL << n) - 1; for (long long i = 1; i <= totalMoves; i++) { int disk = __builtin_ctzll(i) + 1; // Print movement according to Gray code transitions int src = (i & (i - 1)) % 3; int dst = ((i | (i - 1)) + 1) % 3; // Map 0, 1, 2 to from, to, aux } return totalMoves; }}; int main() { Solution sol; cout << "Total moves: " << sol.tohBitwise(3, 1, 3, 2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N)— Generates exactly 2N - 1 steps with O(1) bitwise operations per step. - Space complexity:
O(1)— Uses constant auxiliary space.