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]
Solution 1
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 ...