DSA Explorer
QuicksortMerge SortBubble SortInsertion SortSelection SortHeap SortCounting SortRadix SortBucket SortShell SortTim SortCocktail Shaker SortComb SortGnome SortPancake SortPatience SortCycle SortStrand SortWiggle Sort (Wave Sort)Bead Sort (Gravity Sort)Binary Insertion SortBitonic SortBogo Sort (Stupid Sort)Stooge SortOdd-Even Sort (Brick Sort)Pigeonhole SortIntro Sort (Introspective Sort)Tree Sort (BST Sort)Dutch National Flag (3-Way Partitioning)
Binary SearchLinear SearchJump SearchInterpolation SearchExponential SearchTernary SearchFibonacci SearchQuick Select (k-th Smallest)Median of Medians (Deterministic Select)Hill climbingSimulated AnnealingTabu SearchBinary Tree DFS SearchSentinel Linear SearchDouble Linear SearchTernary Search (Unimodal Function)Search in 2D Matrix
Binary Search Tree (BST)StackQueueHash Table (Hash Map)Heap (Priority Queue)Linked ListTrie (Prefix Tree)Binary TreeTrie (Prefix Tree)Floyd's Cycle Detection (Tortoise and Hare)Merge Two Sorted Linked ListsCheck if Linked List is PalindromeFind Middle of Linked ListBalanced Parentheses (Valid Parentheses)Next Greater ElementInfix to Postfix ConversionMin Stack (O(1) getMin)Largest Rectangle in HistogramDaily Temperatures (Monotonic Stack)Evaluate Reverse Polish NotationInfix Expression Evaluation (Two Stacks)Min Heap & Max HeapSliding Window MaximumTrapping Rain WaterRotate Matrix 90 DegreesSpiral Matrix TraversalSet Matrix ZeroesHash Table with ChainingOpen Addressing (Linear Probing)Double HashingCuckoo Hashing
Depth-First Search (DFS)Breadth-First Search (BFS)Dijkstra's AlgorithmFloyd-Warshall AlgorithmKruskal's AlgorithmPrim's AlgorithmTopological SortA* Pathfinding AlgorithmKahn's Algorithm (Topological Sort)Ford-Fulkerson Max FlowEulerian Path/CircuitBipartite Graph CheckBorůvka's Algorithm (MST)Bidirectional DijkstraPageRank AlgorithmBellman-Ford AlgorithmTarjan's Strongly Connected ComponentsArticulation Points (Cut Vertices)Find Bridges (Cut Edges)Articulation Points (Cut Vertices)Finding Bridges (Cut Edges)
0/1 Knapsack ProblemLongest Common Subsequence (LCS)Edit Distance (Levenshtein Distance)Longest Increasing Subsequence (LIS)Coin Change ProblemFibonacci Sequence (DP)Matrix Chain MultiplicationRod Cutting ProblemPalindrome Partitioning (Min Cuts)Subset Sum ProblemWord Break ProblemLongest Palindromic SubsequenceMaximal Square in MatrixInterleaving StringEgg Drop ProblemUnique Paths in GridCoin Change II (Count Ways)Decode WaysWildcard Pattern MatchingRegular Expression MatchingDistinct SubsequencesMaximum Product SubarrayHouse RobberClimbing StairsPartition Equal Subset SumKadane's Algorithm (Maximum Subarray)
A* Search AlgorithmConvex Hull (Graham Scan)Line Segment IntersectionCaesar CipherVigenère CipherRSA EncryptionHuffman CompressionRun-Length Encoding (RLE)Lempel-Ziv-Welch (LZW)Canny Edge DetectionGaussian Blur FilterSobel Edge FilterHarris Corner DetectionHistogram EqualizationMedian FilterLaplacian FilterMorphological ErosionMorphological DilationImage Thresholding (Otsu's Method)Conway's Game of LifeLangton's AntRule 30 Cellular AutomatonFast Fourier Transform (FFT)Butterworth FilterSpectrogram (STFT)
Knuth-Morris-Pratt (KMP) AlgorithmRabin-Karp AlgorithmBoyer-Moore AlgorithmAho-Corasick AlgorithmManacher's AlgorithmSuffix ArraySuffix Tree (Ukkonen's Algorithm)Trie for String MatchingEdit Distance for StringsLCS for String MatchingHamming DistanceJaro-Winkler DistanceDamerau-Levenshtein DistanceBitap Algorithm (Shift-Or, Baeza-Yates-Gonnet)Rolling Hash (Rabin-Karp Hash)Manacher's AlgorithmZ AlgorithmLevenshtein Distance

Tower of Hanoi

Recursion
O(2^n) time, O(n) recursion stack space
Intermediate

Tower of Hanoi is a classic mathematical puzzle invented by French mathematician Édouard Lucas in 1883. The puzzle consists of three rods and n disks of different sizes that can slide onto any rod. The objective is to move the entire stack from one rod to another, following rules: (1) only one disk can be moved at a time, (2) only the top disk from any rod can be moved, (3) a larger disk cannot be placed on a smaller disk. The elegant recursive solution requires exactly 2^n - 1 moves.

Prerequisites:
Recursion
Mathematical induction
Stack concept

Visualization

Interactive visualization for Tower of Hanoi

Tower of Hanoi Visualization

Classic recursion problem: Move all disks from left to right tower using middle as auxiliary

Source
4
3
2
1
Auxiliary
Destination

Time Complexity: O(2n)

Space Complexity: O(n) recursion depth

Recurrence: T(n) = 2T(n-1) + 1

Rules:

  • Move one disk at a time
  • Larger disk cannot be on smaller disk
  • Only top disk can be moved
  • Minimum moves = 2n - 1

Interactive visualization with step-by-step execution

Implementation

Language:
1function towerOfHanoi(n: number, from: string = 'A', to: string = 'C', aux: string = 'B'): void {
2  if (n === 1) {
3    console.log(`Move disk 1 from ${from} to ${to}`);
4    return;
5  }
6  
7  towerOfHanoi(n - 1, from, aux, to);
8  console.log(`Move disk ${n} from ${from} to ${to}`);
9  towerOfHanoi(n - 1, aux, to, from);
10}
11
12// With move counting
13function towerOfHanoiMoves(n: number): number {
14  if (n === 1) return 1;
15  return 2 * towerOfHanoiMoves(n - 1) + 1;
16}
17
18// Iterative solution (advanced)
19function towerOfHanoiIterative(n: number): void {
20  const totalMoves = Math.pow(2, n) - 1;
21  const src = 'A', dest = 'C', aux = 'B';
22  
23  for (let i = 1; i <= totalMoves; i++) {
24    if (i % 3 === 1) {
25      console.log(`Move disk from ${src} to ${dest}`);
26    } else if (i % 3 === 2) {
27      console.log(`Move disk from ${src} to ${aux}`);
28    } else {
29      console.log(`Move disk from ${aux} to ${dest}`);
30    }
31  }
32}

Deep Dive

Theoretical Foundation

Tower of Hanoi perfectly demonstrates recursion and mathematical induction. The solution is recursive: to move n disks from source to destination using auxiliary, we (1) move n-1 disks from source to auxiliary (recursive call), (2) move largest disk from source to destination (base operation), (3) move n-1 disks from auxiliary to destination (recursive call). Base case: moving 1 disk is trivial. The number of moves T(n) = 2T(n-1) + 1, which solves to 2^n - 1. This is optimal - no algorithm can solve it in fewer moves. The puzzle has applications in backup rotation, algorithm analysis, and teaching recursion.

Complexity

Time

Best

O(2^n)

Average

O(2^n)

Worst

O(2^n)

Space

Required

O(n) recursion stack

Applications

Industry Use

1

Teaching recursion in computer science courses

2

Backup rotation strategies (Grandfather-Father-Son)

3

Algorithm analysis and complexity theory

4

Puzzle games and brain teasers

5

Understanding exponential growth

6

Job scheduling with dependencies

Use Cases

Recursion teaching
Puzzle solving
Backup rotation
Algorithm analysis

Related Algorithms

Generate All Permutations

Generate all possible arrangements (permutations) of n distinct elements. For n elements, there are exactly n! permutations. This classic backtracking problem demonstrates recursive exploration of the solution space, where we systematically build permutations by choosing elements and backtracking when complete. Used in combinatorics, constraint satisfaction, and optimization problems.

Recursion

Generate All Combinations

Generate all C(n,k) combinations - all possible selections of k elements from n elements where order doesn't matter. Unlike permutations, {1,2,3} and {3,2,1} are the same combination. Uses backtracking to explore choices systematically, ensuring each combination is counted once. Fundamental in statistics, probability, lottery systems, and feature selection in machine learning.

Recursion

Generate All Subsets (Power Set)

Generate the power set - all 2^n possible subsets of an n-element set, including the empty set and the set itself. For example, subsets of {1,2,3} are: {}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}. Can be elegantly solved using recursion, iteration, or bit manipulation. Essential in combinatorial optimization and constraint satisfaction.

Recursion

Quicksort

A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.

Sorting
DSA Explorer

Master Data Structures and Algorithms through interactive visualizations and detailed explanations. Our platform helps you understand complex concepts with clear examples and real-world applications.

Quick Links

  • About DSA Explorer
  • All Algorithms
  • Data Structures
  • Contact Support

Legal

  • Privacy Policy
  • Terms of Service
  • Cookie Policy
  • Code of Conduct

Stay Updated

Subscribe to our newsletter for the latest algorithm explanations, coding challenges, and platform updates.

We respect your privacy. Unsubscribe at any time.

© 2026 Momin Studio. All rights reserved.

SitemapAccessibility
v1.0.0