๐Ÿ—“๏ธ Day 16: Recursion

๐Ÿง  Concept Deep Dive

Recursion is a method of solving problems where a function calls itself.

A recursive function typically solves a small piece of the problem and delegates the rest to itself.

To be valid, every recursive function must follow two rules:

  1. Base Case โ€“ the condition to stop recursion
  2. Recursive Case โ€“ how the problem is reduced and the function calls itself

๐Ÿ›ก๏ธ Think Like a Stack

Each recursive call is added to the call stack, and the function pauses until the recursive call finishes. After reaching the base case, calls start unwinding from the stack.

๐Ÿ“ฆ Stack Trace Example:

factorial(3)
-> 3 * factorial(2)
  -> 2 * factorial(1)
    -> 1 (base case)

๐Ÿ” Classic Recursion Pattern

function recurse(problem: Problem): ReturnType {
  if (baseCase(problem)) {
    return baseResult;
  }

  // reduce the problem
  return combine(
    currentWork,
    recurse(smallerProblem)
  );
}

๐Ÿ’ก Example: Factorial

function factorial(n: number): number {
  if (n <= 1) return 1;         // base case
  return n * factorial(n - 1);  // recursive call
}

๐Ÿ”ช Example

Input: factorial(5)
Output: 120

Explanation:
5 * 4 * 3 * 2 * 1 = 120

๐Ÿ’ก Example: Fibonacci

function fibonacci(n: number): number {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

๐Ÿ”ช Example

Input: fibonacci(6)
Output: 8

โš ๏ธ Note: This has exponential time complexity. Use memoization (covered later) to improve.


๐Ÿง  Real-world Analogy

Recursion is like stacking dinner plates.

  • Every plate you stack is like a function call.
  • When you're done stacking (base case), you start removing them in reverse order โ€” just like unwinding the recursive stack.

๐Ÿ“Š Big O Complexity

Function Time Complexity Space Complexity (stack)
Factorial O(n) O(n)
Fibonacci (naive) O(2โฟ) O(n)

๐Ÿ”ช LeetCode-style Homework

Problem: Reverse a String (recursive)

Write a function to reverse a string using recursion.

function reverseString(str: string): string {
  if (str.length <= 1) return str;
  return reverseString(str.slice(1)) + str[0];
}

Example

Input: "hello"
Output: "olleh"

โš ๏ธ Common Pitfalls

  • Missing a base case causes infinite recursion (stack overflow)
  • Forgetting to return the result of the recursive call
  • Not reducing the problem each time

๐Ÿ“† Summary

  • Recursion solves a big problem by breaking it into smaller versions of itself
  • Every recursion needs a base case
  • Stack memory is a major constraint
  • Learn to visualize how recursion flows

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 17: Backtracking

This page was last edited on 2025-08-01 08:35

Powered by Wiki|Docs

This page was last edited on 2025-08-01 08:35

Tri Nguyen
No Copyright

Powered by Wiki|Docs