Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
      • Data Structures Solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerRank Gena Playing Hanoi problem solution

YASH PAL, 31 July 202423 January 2026

In this HackerRank Gena Playing Hanoi problem solution, The Tower of Hanoi is a famous game consisting of 3 rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game’s objective is to move the entire stack to another rod, obeying the following rules:

  1. Only one disk can be moved at a time.
  2. In one move, remove the topmost disk from one rod and move it to another rod.
  3. No disk may be placed on top of a smaller disk.

Gena has a modified version of the Tower of Hanoi. This game of Hanoi has 4 rods and n disks ordered by ascending size. Gena has already made a few moves following the rules above. Given the state of Gena’s Hanoi, determine the minimum number of moves needed to restore the tower to its original state with all disks on rod 1.

HackerRank Gena Playing Hanoi problem solution

HackerRank Gena Playing Hanoi problem solution in Python.

from collections import deque

def tuplify(x):
    return tuple(tuple(i) for i in x)

def moves(rods):
    for x in range(4):
        if rods[x]:
            for y in range(4):
                if not rods[y] or rods[y][-1] > rods[x][-1]:
                    yield (x, y)

def do_move(rods, x, y):
    rods = [list(r) for r in rods]
    rods[y].append(rods[x].pop())
    rods[1:4] = sorted(rods[1:4], key=lambda t: t[-1] if t else 0)
    return tuplify(rods)

def bfs(rods, n):
    start = (tuplify(rods), 0)
    visited = set()
    visited.add(start)
    q = deque([start])
    while q:
        cur, depth = q.popleft()
        if all(len(r) == 0 for r in cur[1:]):
            return depth
        for x, y in moves(cur):
            child = do_move(cur, x, y)
            if child not in visited:
                visited.add(child)
                q.append((child, depth + 1))
    return -1

n = int(input())
rods = [[] for _ in range(4)]
for i, disk in enumerate(map(int, input().split())):
    rods[disk-1] = [i] + rods[disk-1]
print(bfs(rods, n))

Gena Playing Hanoi problem solution in Java.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {



    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int ndisc = scan.nextInt();
        int start = 0;
        for (int h = 1; h <= ndisc; ++h) {
            int rod = scan.nextInt();
            --rod;
            start = move(start, rod, h);

        }
        scan.close();
       
        System.out.print(solve(ndisc, start));
    }

    private static int move(int state, int rod, int disc) {
        return (state & ~(3 << 2 * (disc - 1))) | rod << 2 * (disc - 1);
    }

    private static int getDisc(int ndisc, int state, int rod) {

        int disc = ndisc + 1;
        for (int h = ndisc; h != 0; --h) {
            int r = 3 & state >> 2 * (h - 1);
            if (r == rod) {
                disc = h;
            }
        }
        return disc;
    }

    private static long solve(int ndisc, int start) {
        final int win = 0;
        if (start == win) {
            return 0;
        }
        LinkedList<Integer> bfs = new LinkedList<>();
        bfs.addLast(start);
        List<Integer> depth = Arrays.asList(new Integer[1 << 2 * ndisc]);
        depth.set(start, 0);
        while (true) {
            int par = bfs.getFirst();
            bfs.removeFirst();
            int[] d = new int[4];
            for (int rod = 0; rod < 4; ++rod) {
                d[rod] = getDisc(ndisc, par, rod);
            }
            for (int from = 0; from < 4; ++from) {
                if (d[from] == ndisc + 1) {
                    continue;
                }
                for (int to = 0; to < 4; ++to) {
                    if (d[to] > d[from]) {
                        int ch = move(par, to, d[from]);
                        if (ch == win) {
                            return 1 + depth.get(par);
                        }
                        if (depth.get(ch) == null && ch != start) {
                            depth.set(ch, 1 + depth.get(par));
                                                  
                            bfs.addLast(ch);
                        }
                    }
                }
            }
        }

    }
}

Problem solution in C++.

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

const int Maxn = 10;
const int Inf = 1000000000;

int n;
int dp[1 << 2 * Maxn];

int Get(int mask, int ind)
{
    return (mask & 3 << 2 * ind) >> 2 * ind;    
}

int Set(int mask, int ind, int val)
{
    int got = mask & 3 << 2 * ind;
    mask ^= got;
    mask |= val << 2 * ind;
    return mask;
}

int main(){
    cin >> n;
    fill(dp, dp + (1 << 2 * Maxn), Inf);
    int got = 0;
    for (int i = 0; i < n; i++) {
        int a; scanf("%d", &a); a--;
        got |= a << 2 * i;
    }
    dp[got] = 0;
    queue <int> Q; Q.push(got);
    while (!Q.empty()) {
        int v = Q.front(); Q.pop();
        bool tk[4] = {};
        for (int i = 0; i < n; i++) {
            int my = Get(v, i);
            if (tk[my]) continue;
            for (int j = 0; j < 4; j++) if (my != j && !tk[j]) {
                int u = Set(v, i, j);
                if (dp[v] + 1 < dp[u]) {
                    dp[u] = dp[v] + 1;
                    Q.push(u);
                }
            }
            tk[my] = true;
        }
    }
    printf("%dn", dp[0]);
    return 0;
}

Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

typedef struct _QueueElement {
    int move;
    int state;
} QueueElement;


int N;


#define QUEUE_SIZE (1024*1024*16)
QueueElement queue[QUEUE_SIZE];
char enqueued[QUEUE_SIZE];
int queueCount = 0;
int queueStart = 0;

int emptyQueue()
{
    return (queueCount == 0);
}


void pushQueue(int move, int state)
{
    int index = queueStart + queueCount;
    if (index >= QUEUE_SIZE) {
        index -= QUEUE_SIZE;
    }
    if (enqueued[state] != move) {
        queue[index].move  = move;
        queue[index].state = state;
        enqueued[state] = move;
        queueCount += 1;
    }
}


int popQueue(int *move)
{
    int res = queue[queueStart].state;
    *move = queue[queueStart].move;
    queueStart += 1;
    if (queueStart >= QUEUE_SIZE) {
        queueStart -= QUEUE_SIZE;
    }
    queueCount -= 1;
    return res;
}


void genMoves(int state, int *moves, int *movesCount)
{
    int rod;
    int i = 0;
    int r[4] = { -1, -1, -1, -1 };
    int tmp = state;
    while (tmp) {
        rod = tmp & 0x3;
        if (r[rod] < 0) {
            r[rod] = i;
        }
        tmp >>= 2;
        i += 1;
    }
    *movesCount = 0;
    if (r[0] >= 0) {
        if (r[0] < r[1] || r[1] < 0) {
            moves[*movesCount] = state | (1 << (r[0] * 2));
            *movesCount += 1;
        }
        if (r[0] < r[2] || r[2] < 0) {
            moves[*movesCount] = state | (2 << (r[0] * 2));
            *movesCount += 1;
        }
        if (r[0] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[0] * 2));
            *movesCount += 1;
        }
    }
    if (r[1] >= 0) {
        if (r[1] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(1 << (r[1] * 2)));
            *movesCount += 1;
        }
        if (r[1] < r[2] || r[2] < 0) {
            moves[*movesCount] = state & (~(1 << (r[1] * 2)));
            moves[*movesCount] |= (2 << (r[1] * 2));
            *movesCount += 1;
        }
        if (r[1] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[1] * 2));
            *movesCount += 1;
        }
    }
    if (r[2] >= 0) {
        if (r[2] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(2 << (r[2] * 2)));
            *movesCount += 1;
        }
        if (r[2] < r[1] || r[1] < 0) {
            moves[*movesCount] = state & (~(2 << (r[2] * 2)));
            moves[*movesCount] |= (1 << (r[2] * 2));
            *movesCount += 1;
        }
        if (r[2] < r[3] || r[3] < 0) {
            moves[*movesCount] = state | (3 << (r[2] * 2));
            *movesCount += 1;
        }
    }
    if (r[3] >= 0) {
        if (r[3] < r[0] || r[0] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            *movesCount += 1;
        }
        if (r[3] < r[1] || r[1] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            moves[*movesCount] |= (1 << (r[3] * 2));
            *movesCount += 1;
        }
        if (r[3] < r[2] || r[2] < 0) {
            moves[*movesCount] = state & (~(3 << (r[3] * 2)));
            moves[*movesCount] |= (2 << (r[3] * 2));
            *movesCount += 1;
        }
    }
}


int main()
{
    int i;
    for (i = 0; i < QUEUE_SIZE; ++i) {
        enqueued[i] = -1;
    }
    scanf("%d", &N);
    {
        int state = 0;
        int tmp;
        for (i = 0; i < N; ++i) {
            scanf("%d", &tmp);
            state |= (tmp - 1) << (i * 2);
        }
        pushQueue(0, state);
    }

    {
        int state;
        int move;
        int moves[6];
        int movesCount;

        while (! emptyQueue()) {
            state = popQueue(&move);
            if (! state) {
                break;
            }

            genMoves(state, moves, &movesCount);
            for (i = 0; i < movesCount; ++i) {
                pushQueue(move + 1, moves[i]);
            }
        }

        printf("%dn", move);
    }

    return 0;
}

Algorithms coding problems solutions AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes