Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Tower of Hanoi Implementation

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Tower of Hanoi Implementation. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Coupa workflow configuration may need to explain a sequence of dependent operations. Implement the Tower of Hanoi algorithm to generate the optimal sequence of disk moves for such a dependency chain.

You are given n disks arranged from largest at the bottom to smallest at the top on a source peg. Move all disks to a target peg using an auxiliary peg.

A move transfers exactly one top disk from one peg to another. A larger disk may never be placed on a smaller disk. Return the complete sequence of moves in execution order.

Formal Specification

Implement solve_hanoi(n, source, auxiliary, target). n is a non-negative integer, and each peg name is a string. Return a list of tuples, where each tuple has the form (from_peg, to_peg). The sequence must use the minimum possible number of moves, 2^n - 1 for n > 0.

The function must not mutate any caller-provided object and must handle n = 0 by returning an empty list.

Constraints

  • 0 <= n <= 15
  • Peg names are non-empty strings
  • The three peg names are distinct
  • Return exactly 2^n - 1 moves when n > 0
  • Each move is a tuple of two peg names

Function Signature

def solve_hanoi(n, source, auxiliary, target):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output