Skip to content

Commit 8bf29fe

Browse files
authored
merge: Optimize the space complexity of the fibonacci algo (#899)
* docs: update js doc * feat: add number type validation condition * pref: Optimize space complexity remove the Array from the algo and used two flag varible to calculate last two numbers & optimize the sapce complexity O(n) to O(1) * test: add test case for invalid types
1 parent 743b317 commit 8bf29fe

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed
+16-8
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,27 @@
11
/**
2-
* @function Fibonacci
2+
* @function fibonacci
33
* @description Fibonacci is the sum of previous two fibonacci numbers.
44
* @param {Integer} N - The input integer
55
* @return {Integer} fibonacci of N.
66
* @see [Fibonacci_Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)
77
*/
88
const fibonacci = (N) => {
9-
// creating array to store values
10-
const memo = new Array(N + 1)
11-
memo[0] = 0
12-
memo[1] = 1
13-
for (let i = 2; i <= N; i++) {
14-
memo[i] = memo[i - 1] + memo[i - 2]
9+
if (!Number.isInteger(N)) {
10+
throw new TypeError('Input should be integer')
1511
}
16-
return memo[N]
12+
13+
// memoize the last two numbers
14+
let firstNumber = 0
15+
let secondNumber = 1
16+
17+
for (let i = 1; i < N; i++) {
18+
const sumOfNumbers = firstNumber + secondNumber
19+
// update last two numbers
20+
firstNumber = secondNumber
21+
secondNumber = sumOfNumbers
22+
}
23+
24+
return N ? secondNumber : firstNumber
1725
}
1826

1927
export { fibonacci }

Dynamic-Programming/tests/FibonacciNumber.test.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { fibonacci } from '../FibonacciNumber'
22

3-
describe('FibonacciNumber', () => {
3+
describe('Testing FibonacciNumber', () => {
4+
it('Testing for invalid type', () => {
5+
expect(() => fibonacci('0')).toThrowError()
6+
expect(() => fibonacci('12')).toThrowError()
7+
expect(() => fibonacci(true)).toThrowError()
8+
})
9+
410
it('fibonacci of 0', () => {
511
expect(fibonacci(0)).toBe(0)
612
})

0 commit comments

Comments
 (0)