Day 16: Recursion Explained in a Beginner-Friendly Way
Screenshot:-
Recursion can be a tricky concept, but it's incredibly powerful. Think of it as a function calling itself to solve smaller instances of the same problem. Let's dive into some tasks that will help you understand recursion better.
Activity 1: Basic Recursion
Task 1: Factorial Calculation
The factorial of a number is the product of all positive integers less than or equal to that number. For example, factorial(5) is 5×4×3×2×1.
Example Code:
function factorial(val) {
if (val === 0) return 1; // 0! is 1
if (val === 1) return 1; // 1! is 1
return val * factorial(val - 1); // Recursive call
}
console.log(factorial(5)); // Output: 120
console.log(factorial(3)); // Output: 6
Explanation:
Base Cases: If
val
is 0 or 1, the function returns 1.Recursive Case: The function calls itself with
val - 1
and multiplies the result byval
.
Task 2: Fibonacci Sequence
The Fibonacci sequence is a series where each number is the sum of the two preceding ones, starting from 0 and 1.
Example Code:
function fibonacci(n) {
if (n === 0) {
return 0; // Base case
}
if (n === 1) {
return 1; // Base case
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}
console.log(fibonacci(6)); // Output: 8
console.log(fibonacci(10)); // Output: 55
Explanation:
Base Cases: If
n
is 0 or 1, returnn
.Recursive Case: Return the sum of
fibonacci(n - 1)
andfibonacci(n - 2)
.
Activity 2: Recursion with Arrays
Task 3: Sum of Array Elements
Sum all elements in an array recursively.
Example Code:
function sumArray(arr) {
if (arr.length === 0) {
return 0; // Base case: empty array
}
return arr[0] + sumArray(arr.slice(1)); // Recursive call
}
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
Explanation:
Base Case: If the array is empty, return 0.
Recursive Case: Return the first element plus the sum of the rest of the array.
Task 4: Maximum Element in an Array
Find the maximum element in an array recursively.
Example Code:
function maxArray(arr) {
if (arr.length === 1) {
return arr[0]; // Base case: single element
}
return Math.max(arr[0], maxArray(arr.slice(1))); // Recursive call
}
console.log(maxArray([1, 5, 3, 9, 2])); // Output: 9
Explanation:
Base Case: If the array has one element, return it.
Recursive Case: Return the maximum of the first element and the maximum of the rest of the array.
Activity 3: String Manipulation with Recursion
Task 5: Reverse a String
Reverse a string recursively.
Example Code:
function reverse(string) {
if (string === "") {
return ""; // Base case: empty string
}
return reverse(string.substr(1)) + string.charAt(0); // Recursive call
}
console.log(reverse("hello")); // Output: "olleh"
Explanation:
Base Case: If the string is empty, return an empty string.
Recursive Case: Return the reverse of the substring (excluding the first character) plus the first character.
Task 6: Check Palindrome
Check if a string is a palindrome recursively.
Example Code:
function isPalindrome(str) {
if (str.length <= 1) {
return true; // Base case: empty string or single character
}
if (str[0] !== str[str.length - 1]) {
return false; // If first and last characters don't match
}
return isPalindrome(str.slice(1, str.length - 1)); // Recursive call
}
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("Alpit")); // Output: false
Explanation:
Base Case: If the string is empty or a single character, it's a palindrome.
Recursive Case: Check if the first and last characters match, then check the substring excluding those characters.
Activity 4: Recursive Search
Task 7: Binary Search
Perform a binary search on a sorted array.
Example Code:
function binarySearch(arr, target, left = 0, right = arr.length - 1) {
if (left > right) {
return -1; // Base case: not found
}
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // Found target
}
if (arr[mid] > target) {
return binarySearch(arr, target, left, mid - 1); // Search left half
}
return binarySearch(arr, target, mid + 1, right); // Search right half
}
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7], 5)); // Output: 4
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7], 8)); // Output: -1
Explanation:
Base Case: If
left
exceedsright
, the target is not in the array.Recursive Case: Compare the middle element with the target and search the appropriate half.
Task 8: Count Occurrences
Count the occurrences of a target element in an array.
Example Code:
function countOccurrence(arr, target) {
if (arr.length === 0) {
return 0; // Base case: empty array
}
if (arr[0] === target) {
return 1 + countOccurrence(arr.slice(1), target); // Recursive call
}
return countOccurrence(arr.slice(1), target); // Recursive call
}
console.log(countOccurrence([1, 2, 3, 4, 1, 1, 2], 1)); // Output: 3
Explanation:
Base Case: If the array is empty, return 0.
Recursive Case: Check if the first element matches the target, then count the rest.
Activity 5: Tree Traversal (Optional)
Task 9: In-order Traversal
Perform an in-order traversal of a binary tree.
Example Code:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function inOrderTraversal(node) {
if (node === null) {
return;
}
inOrderTraversal(node.left);
console.log(node.value);
inOrderTraversal(node.right);
}
// Example Usage
const root = new TreeNode(4);
root.left = new TreeNode(2);
root.right = new TreeNode(6);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);
root.right.left = new TreeNode(5);
root.right.right = new TreeNode(7);
inOrderTraversal(root); // Output: 1, 2, 3, 4, 5, 6, 7
Explanation:
Base Case: If the node is null, return.
Recursive Case: Traverse the left subtree, visit the node, then traverse the right subtree.
Task 10: Tree Depth
Calculate the depth of a binary tree.
Example Code:
function treeDepth(node) {
if (node === null) {
return 0; // Base case: empty tree
}
const leftDepth = treeDepth(node.left);
const rightDepth = treeDepth(node.right);
return Math.max(leftDepth, rightDepth) + 1; // Recursive call
}
console.log(treeDepth(root)); // Output: 3
Explanation:
Base Case: If the node is null, return 0.
Recursive Case: Calculate the depth of the left and right subtrees, and return the greater depth plus 1.
Conclusion
By practicing these tasks, you'll understand how recursion works and how to apply it to solve various problems. Keep experimenting and breaking down problems into smaller parts that you can solve recursively. Happy coding!