Skip to content
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

Fix Fibonacci problem for negative numbers #55

Merged
merged 9 commits into from
Oct 10, 2019
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
- [Remove Consecutive Repeated Digits](src/_DataStructures_/Stack/remove-consecutive-repeated-digits)
- [Implement 2 Stacks using Single Array](src/_DataStructures_/Stack/2-stacks-using1-array)


- [Queue](src/_DataStructures_/Queue)

- [Weave](src/_DataStructures_/Queue/weave)
Expand Down
13 changes: 10 additions & 3 deletions src/_Classics_/fibonacci/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// the algorithm has time complexity of O(n^2), very bad!
function fibonacci(position) {
// if position is 1 or 2, the number in fibonacci sequence will be 1
if (position <= 1) {
if (position === 1 || position === 0) {
return position;
} else if (position < 0) {
throw new Error('Invalid Position');
}

// else the element in fibonacci sequence will be the sum of
Expand All @@ -26,8 +28,11 @@ function fibonacciMemoized(index, cache) {
if (cache[index]) {
return cache[index];
} else {
if (index <=1) {
if (index === 1 || index === 0) {
return index;
} else if (index < 0) {
throw new Error('Invalid Position');

} else {
cache[index] =
fibonacciMemoized(index - 1, cache) +
Expand All @@ -43,8 +48,10 @@ function fibonacciMemoized(index, cache) {

function fibonacciTabular(n) {
const table = [0, 1];
if (n <= 1) {
if (n === 1 || n === 0) {
return n;
} else if (n < 0) {
throw new Error('Invalid Position');
}
for (let i = 2; i <= n; i += 1) {
table[i] = table[i - 1] + table[i - 2];
Expand Down
2 changes: 1 addition & 1 deletion src/_DataStructures_/Queue/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ class Queue {
}
}

module.exports = Queue;
module.exports = Queue;