Skip to content

Commit 597cd0e

Browse files
SumeetHaryaniTheSTL
authored andcommitted
Fix Fibonacci problem for negative numbers (knaxus#55)
* handling fibonacci for negative numbers and 0 * fix fibonacci problem for negative numbers
1 parent bfbee74 commit 597cd0e

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
3030
- [Remove Consecutive Repeated Digits](src/_DataStructures_/Stack/remove-consecutive-repeated-digits)
3131
- [Implement 2 Stacks using Single Array](src/_DataStructures_/Stack/2-stacks-using1-array)
3232

33+
3334
- [Queue](src/_DataStructures_/Queue)
3435

3536
- [Weave](src/_DataStructures_/Queue/weave)

src/_Classics_/fibonacci/index.js

+10-3
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
// the algorithm has time complexity of O(n^2), very bad!
33
function fibonacci(position) {
44
// if position is 1 or 2, the number in fibonacci sequence will be 1
5-
if (position <= 1) {
5+
if (position === 1 || position === 0) {
66
return position;
7+
} else if (position < 0) {
8+
throw new Error('Invalid Position');
79
}
810

911
// else the element in fibonacci sequence will be the sum of
@@ -26,8 +28,11 @@ function fibonacciMemoized(index, cache) {
2628
if (cache[index]) {
2729
return cache[index];
2830
} else {
29-
if (index <=1) {
31+
if (index === 1 || index === 0) {
3032
return index;
33+
} else if (index < 0) {
34+
throw new Error('Invalid Position');
35+
3136
} else {
3237
cache[index] =
3338
fibonacciMemoized(index - 1, cache) +
@@ -43,8 +48,10 @@ function fibonacciMemoized(index, cache) {
4348

4449
function fibonacciTabular(n) {
4550
const table = [0, 1];
46-
if (n <= 1) {
51+
if (n === 1 || n === 0) {
4752
return n;
53+
} else if (n < 0) {
54+
throw new Error('Invalid Position');
4855
}
4956
for (let i = 2; i <= n; i += 1) {
5057
table[i] = table[i - 1] + table[i - 2];

src/_DataStructures_/Queue/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,4 @@ class Queue {
1717
}
1818
}
1919

20-
module.exports = Queue;
20+
module.exports = Queue;

0 commit comments

Comments
 (0)