File tree 3 files changed +12
-4
lines changed
3 files changed +12
-4
lines changed Original file line number Diff line number Diff line change @@ -30,6 +30,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
30
30
- [ Remove Consecutive Repeated Digits] ( src/_DataStructures_/Stack/remove-consecutive-repeated-digits )
31
31
- [ Implement 2 Stacks using Single Array] ( src/_DataStructures_/Stack/2-stacks-using1-array )
32
32
33
+
33
34
- [ Queue] ( src/_DataStructures_/Queue )
34
35
35
36
- [ Weave] ( src/_DataStructures_/Queue/weave )
Original file line number Diff line number Diff line change 2
2
// the algorithm has time complexity of O(n^2), very bad!
3
3
function fibonacci ( position ) {
4
4
// if position is 1 or 2, the number in fibonacci sequence will be 1
5
- if ( position <= 1 ) {
5
+ if ( position === 1 || position === 0 ) {
6
6
return position ;
7
+ } else if ( position < 0 ) {
8
+ throw new Error ( 'Invalid Position' ) ;
7
9
}
8
10
9
11
// else the element in fibonacci sequence will be the sum of
@@ -26,8 +28,11 @@ function fibonacciMemoized(index, cache) {
26
28
if ( cache [ index ] ) {
27
29
return cache [ index ] ;
28
30
} else {
29
- if ( index <= 1 ) {
31
+ if ( index === 1 || index === 0 ) {
30
32
return index ;
33
+ } else if ( index < 0 ) {
34
+ throw new Error ( 'Invalid Position' ) ;
35
+
31
36
} else {
32
37
cache [ index ] =
33
38
fibonacciMemoized ( index - 1 , cache ) +
@@ -43,8 +48,10 @@ function fibonacciMemoized(index, cache) {
43
48
44
49
function fibonacciTabular ( n ) {
45
50
const table = [ 0 , 1 ] ;
46
- if ( n <= 1 ) {
51
+ if ( n === 1 || n === 0 ) {
47
52
return n ;
53
+ } else if ( n < 0 ) {
54
+ throw new Error ( 'Invalid Position' ) ;
48
55
}
49
56
for ( let i = 2 ; i <= n ; i += 1 ) {
50
57
table [ i ] = table [ i - 1 ] + table [ i - 2 ] ;
Original file line number Diff line number Diff line change @@ -17,4 +17,4 @@ class Queue {
17
17
}
18
18
}
19
19
20
- module . exports = Queue ;
20
+ module . exports = Queue ;
You can’t perform that action at this time.
0 commit comments