Generate Fibonacci sequence

Generate Fibonacci numbers iteratively by keeping the last two values and adding them, which is O(n) time and O(1) space; avoid the naive recursive version (O(2^n)), and switch to BigInt beyond the 78th number, where Number loses precision.

Approaches

  1. Iterative (best default): two variables, one loop.
  2. Generator: function* yielding forever; the consumer decides how many to take.
  3. Naive recursion: fib(n) = fib(n-1) + fib(n-2). Elegant but exponential, because the same values are recomputed again and again (fib(40) makes over 300 million calls).
  4. Memoised recursion / dynamic programming: cache results, O(n).
  5. Matrix exponentiation / fast doubling: O(log n), for very large n.

Precision

Number represents integers exactly only up to 2^53 - 1. Fibonacci(79) exceeds that, so results become wrong silently. Use BigInt (0n, 1n) for large terms.

Interview follow-ups

  • Return the nth number vs return the first n numbers.
  • Handle n = 0, n = 1 and negative input.
  • Discuss time and space complexity of each approach.
  • Explain why recursion is slow (overlapping subproblems) and how memoisation fixes it, which leads into dynamic programming.

Code example

js
1// 1. Iterative: O(n) time, O(1) space
2function fib(n) {
3 if (!Number.isInteger(n) || n < 0) throw new RangeError("n must be a non-negative integer");
4 let [a, b] = [0, 1];
5 for (let i = 0; i < n; i++) [a, b] = [b, a + b];
6 return a;
7}
8
9// First n numbers
10const sequence = (count) => Array.from({ length: count }, (_, i) => fib(i));
11console.log(sequence(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
12
13// 2. Generator: lazy and unbounded
14function* fibonacci() {
15 let [a, b] = [0n, 1n];
16 while (true) {
17 yield a;
18 [a, b] = [b, a + b];
19 }
20}
21const firstTen = [];
22for (const n of fibonacci()) {
23 if (firstTen.length === 10) break;
24 firstTen.push(Number(n));
25}
26console.log(firstTen.join(", ")); // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
27
28// 3. Naive recursion is exponential
29let calls = 0;
30const naive = (n) => (calls++, n < 2 ? n : naive(n - 1) + naive(n - 2));
31naive(25);
32console.log("naive calls for n=25:", calls); // 242785
33
34// 4. Precision: Number breaks after fib(78), BigInt stays exact
35const fibBig = (n) => {
36 let [a, b] = [0n, 1n];
37 for (let i = 0; i < n; i++) [a, b] = [b, a + b];
38 return a;
39};
40console.log(fib(78), fibBig(78)); // 8944394323791464 8944394323791464n
41console.log(fib(90), fibBig(90)); // 2880067194370816000 2880067194370816120n - the Number is off by 120

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app