-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfibonacci.ts
45 lines (37 loc) · 1012 Bytes
/
fibonacci.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Wikipedia: "The Fibonacci sequence, in which each number is the sum of the two preceding ones."
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
// [0, 1 + 0 = 1]
// [1, 1 + 0 = 1]
// [1, 1 + 1 = 2]
// [2, 1 + 2 = 3]
// [3, 3 + 2 = 5]
// ...
export const FIBONACCI_CACHE: { [key: number]: number } = {};
// O(n) space
// O(2^n) runtime
export const fibonacciRecursive = (n: number): number => {
if (n < 2) {
return n;
}
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
};
// O(1) space
// O(n) runtime
export const fibonacciIterative = (n: number): number => {
let nMinus1 = 0;
let nMinus2 = 1;
for (let i = 0; i < n; i++) {
[nMinus1, nMinus2] = [nMinus2, nMinus1 + nMinus2];
}
return nMinus1;
};
// O(n) space
// O(2^n) -> O(n) runtime
export const fibonacciRecursiveMemoized = (n: number): number => {
if (FIBONACCI_CACHE[n] !== undefined) {
return FIBONACCI_CACHE[n];
}
const f = fibonacciRecursive(n);
FIBONACCI_CACHE[n] = f;
return f;
};