Search⌘ K

Memoized Fibonacci

Explore how to implement and optimize the Fibonacci sequence function using memoization in JavaScript. Understand how storing previously calculated values reduces redundant computations and boosts performance during repeated calls, helping you write efficient algorithms for coding interviews.

We'll cover the following...

Fibonacci

We’ll start with the simple version and create the advanced version further down.

Instructions

Write a function that will take a positive integer n and return an array of length n containing the Fibonacci sequence.

Input: Integer > 0

Output: Array of Numbers

Examples

fibonacci(4); // -> [1, 1, 2, 3]
fibonacci(6); // -> [1, 1, 2, 3, 5, 8]
fibonacci(8); // -> [1, 1, 2, 3, 5, 8, 13, 21]

Node.js
function fibonacci(n) {
// Your code here
}

Solution 1

Node.js
function fibonacci(n) {
const seq = [1, 1];
if(n < 2) {
return seq.slice(0, n);
}
while(seq.length < n) {
const lastItem = seq[seq.length - 1];
const secondLastItem = seq[seq.length - 2];
seq.push(lastItem + secondLastItem);
}
return seq;
}

How it Works

We store the sequence in seq. In the loop, we add up the previous two values in the array and push the sum into the array. We run the loop until we have the array length we want.

Time

Time complexity is:

O(n),

since the number of times ...