DSA Lesson 25 of 33

Recursion

Learn how functions solve problems by calling themselves.

Course Progress76%

Theory

Recursion is a technique where a function calls itself to solve smaller versions of the same problem. Every recursive solution needs a base case that stops the recursion. Recursion is commonly used with trees, graphs, divide-and-conquer and backtracking.

Example

function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); } console.log(factorial(5));

Expected Output

120

Practice

Write a recursive function to calculate the sum of numbers from 1 to n.

Interview Questions

  1. What is recursion?
  2. What is a base case?
  3. Why is a base case important?
  4. Where is recursion commonly used?