Skip to content

Optimize the space complexity of the fibonacci algo #899

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions Dynamic-Programming/FibonacciNumber.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
/**
* @function Fibonacci
* @function fibonacci
* @description Fibonacci is the sum of previous two fibonacci numbers.
* @param {Integer} N - The input integer
* @return {Integer} fibonacci of N.
* @see [Fibonacci_Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)
*/
const fibonacci = (N) => {
// creating array to store values
const memo = new Array(N + 1)
memo[0] = 0
memo[1] = 1
for (let i = 2; i <= N; i++) {
memo[i] = memo[i - 1] + memo[i - 2]
if (!Number.isInteger(N)) {
throw new TypeError('Input should be integer')
}
return memo[N]

// memoize the last two numbers
let firstNumber = 0
let secondNumber = 1

for (let i = 1; i < N; i++) {
const sumOfNumbers = firstNumber + secondNumber
// update last two numbers
firstNumber = secondNumber
secondNumber = sumOfNumbers
}

return N ? secondNumber : firstNumber
}

export { fibonacci }
8 changes: 7 additions & 1 deletion Dynamic-Programming/tests/FibonacciNumber.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { fibonacci } from '../FibonacciNumber'

describe('FibonacciNumber', () => {
describe('Testing FibonacciNumber', () => {
it('Testing for invalid type', () => {
expect(() => fibonacci('0')).toThrowError()
expect(() => fibonacci('12')).toThrowError()
expect(() => fibonacci(true)).toThrowError()
})

it('fibonacci of 0', () => {
expect(fibonacci(0)).toBe(0)
})
Expand Down