Recursion Guide in JavaScript
Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems.
Syntax:
function recursiveFunction(parameters) {
// Base case: stopping condition
if (baseCase) {
return baseCaseValue;
}
// Recursive case: function calls itself
return recursiveFunction(modifiedParameters);
}
Key Components:
- Base Case:
- This is the condition that stops the recursion.
- Without a base case, the function will call itself indefinitely, leading to a stack overflow.
- Example: If calculating the factorial of a number, the base case is when the number is 0 or 1.
- Recursive Case:
- This is where the function calls itself with a modified input.
- The input is typically modified to move closer to the base case.
- Example: For factorial, the recursive case is n * factorial(n - 1).
Example : Factorial of a Number
function factorial(n) {
// Base case: if n is 0 or 1, return 1
if (n === 0 || n === 1) {
return 1;
}
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
Output
120
Why Use Recursion?
Recursion is particularly useful for solving problems that can be divided into smaller, identical problems. Some common use cases include:
- Tree and Graph Traversals: Recursion is ideal for traversing hierarchical data structures like trees and graphs.
- Divide and Conquer Algorithms: Many algorithms, such as Merge Sort and Quick Sort, use recursion to break down problems into smaller subproblems.
- Backtracking: Recursion is often used in backtracking algorithms to explore all possible solutions.
Example 1: Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones (e.g., 0, 1, 1, 2, 3, 5, 8, ...).
function fibonacci(n) {
// Base case: return n if n is 0 or 1
if (n === 0 || n === 1) {
return n;
}
// Recursive case: sum of the two preceding numbers
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // Output: 8
Output
8
Application of Recursion
- Mathematical Computations
- Factorial calculation
- Fibonacci sequence
- Greatest Common Divisor (GCD)
- Data Structures
- Tree traversal (Preorder, Inorder, Postorder)
- Graph traversal (Depth-First Search)
- Linked list operations (Reversal, Searching)
- Sorting Algorithms
- Merge Sort
- Quick Sort
- Backtracking
- N-Queens problem
- Sudoku solver
- Maze solving
- Dynamic Programming
- Fibonacci sequence optimization
- Longest Common Subsequence (LCS)
- Knapsack problem
- File System Operations
- Directory traversal
- Searching for files in nested folders
Tail Recursion
Tail recursion is a special form of recursion where the recursive call is the last operation in the function. This means that the function doesn't perform any additional computation after the recursive call returns. Tail recursion is important because it can be optimized by the compiler or interpreter to avoid growing the call stack, making it more memory-efficient.
Key Characteristics of Tail Recursion
- Last Operation: The recursive call must be the last operation in the function.
- No Pending Work: The function should not perform any computation after the recursive call.
- Optimization: Tail-recursive functions can be optimized into a loop by the compiler or interpreter, avoiding stack overflow.
When to Use Tail Recursion
- Use tail recursion when you need to solve a problem recursively and want to avoid stack overflow.
- Tail recursion is particularly useful for problems that involve large inputs or deep recursion.
Example: Factorial with Tail Recursion
function factorial(n, accumulator = 1) {
// Base case:
if (n === 0 || n === 1) {
return accumulator;
}
// Tail-recursive call:
return factorial(n - 1, n * accumulator);
}
console.log(factorial(5)); // Output: 120
Output
120
Easy Problems on Recursion in JS
- Print 1 to n without loop
- Print n to 1 without loop
- Mean of Array using Recursion
- Sum of natural numbers using recursion
- Decimal to binary number using recursion
- Sum of array elements using recursion
Medium Problems on Recursion in JS
- Binary to Gray code using recursion
- Delete a linked list using recursion
- Product of 2 Numbers using Recursion
- Programs for Printing Pyramid Patterns using Recursion
- Length of longest palindromic sub-string : Recursion
Hard Problems on Recursion in JS
- Check if a string is a scrambled form of another string
- Word Break Problem | DP-32
- Print all palindromic partitions of a string
- N Queen Problem | Backtracking-3
- Algorithm to Solve Sudoku | Sudoku Solver