× logo Home HTML CSS Javascript React-App Angular logo
logo

Mastering Top 10 Javascript Algorithms

**Algorithm Name**: Fibonacci Sequence

* **Questions**:
Does the sequence start with 0 or 1? If asked to compute for a large number, how should I handle it?

* **Time Complexity**:
- Brute Force: O(2^n)
- Optimized: O(n)

* **Space Complexity**:
- Brute Force: O(n)
- Optimized: O(n)

* **Approaches**:
- Brute Force:
Recursively call fibonacci for n-1 and n-2 and add these together
- Optimized: Create a bottom-up approach using memoization to store fibonacci of each number up to n

* **Explanation**:
The Fibonacci sequence is a series of numbers where a number is found by adding up the two numbers before it.
The sequence starts 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
The brute force method recursively calculates each value, while the optimized solution keeps track of previously calculated values to avoid unnecessary recursion.

* **Sample Code**: Javascript

// Brute Force:

fibonacci = (n) => {
if(n <= 1 ) {
return n;
}
return fibonacci(n-1)+ fibonacci(n-2);
}
// Optimized

fibonacciOptimized = (n) => {
let fib = [0, 1];
for (let i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}

//Unit Test
* **Example**:
console.log(fibonacci(6)) // 8
console.log(fibonacciOptimized(6))

- Input: 6
- Output: 8




logo