diff --git a/README.md b/README.md index 545981ac..0c52c6f5 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/_Classics_/fibonacci/index.js b/src/_Classics_/fibonacci/index.js index 6c61bdc1..979fb5c8 100644 --- a/src/_Classics_/fibonacci/index.js +++ b/src/_Classics_/fibonacci/index.js @@ -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 @@ -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) + @@ -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]; diff --git a/src/_DataStructures_/Queue/index.js b/src/_DataStructures_/Queue/index.js index 99d1861c..d51bcab0 100644 --- a/src/_DataStructures_/Queue/index.js +++ b/src/_DataStructures_/Queue/index.js @@ -17,4 +17,4 @@ class Queue { } } -module.exports = Queue; +module.exports = Queue; \ No newline at end of file