Engineered
Recursion

Fibonacci Number

Practice recursive base cases and progress by computing Fibonacci numbers.

Try It Yourself

Use the editor below to compute the nth Fibonacci number recursively. Identify the two base cases and make every other call move toward them.

Submit your implementation when it passes the examples. Use memoization so repeated recursive subproblems are calculated only once.

Fibonacci Number

easyRecursion · Memoization20 minLC 509
Problem

The Fibonacci sequence starts with F(0) = 0 and F(1) = 1. Every later value is the sum of the previous two values.

Given n, return F(n) using a recursive solution.

Example 1:

Input: n = 2
Output: 1

Example 2:

Input: n = 6
Output: 8

Constraints

  • 0 ≤ n ≤ 30
  • Use recursion; memoization is allowed.
0 attempts

Solution

The base cases return 0 and 1 immediately. Every larger Fibonacci number is the sum of the two smaller Fibonacci calls before it.

A memo stores completed results. This keeps the recursive structure while preventing the same Fibonacci value from being expanded many times.

function fib(n) {
  const memo = new Map();

  function calculate(value) {
    if (value <= 1) return value;
    if (memo.has(value)) return memo.get(value);

    const result = calculate(value - 1) + calculate(value - 2);
    memo.set(value, result);
    return result;
  }

  return calculate(n);
}

Big O notation

MeasureComplexityExplanation
TimeO(n)Memoization calculates each Fibonacci value from 0 through n once.
Auxiliary spaceO(n)The memo and recursive call stack can each grow with n.

How is this lesson?