about summary refs log tree commit diff
path: root/scratch/facebook/interview-cake/nth-fibonacci.py
diff options
context:
space:
mode:
authorWilliam Carroll <wpcarro@gmail.com>2020-11-21T14·48+0000
committerWilliam Carroll <wpcarro@gmail.com>2020-11-21T14·48+0000
commit417d3b5fffc081e650ecf16b7f1f14f4fa7c70dd (patch)
tree6a1e3b7ce9dc8a65efd8782d17a818bfc9614705 /scratch/facebook/interview-cake/nth-fibonacci.py
parent70e74a4027a762180840ec79ccec9c8f998a7683 (diff)
Implement a bottom-up fibonacci
The bottom-up solution run in O(n) time instead of O(2^n) time, which the
recursive solution runs as:

```
def fib(n):
    return fib(n - 2) + fib(n - 1)
```

Remember that exponential algorithms are usually recursive algorithms with
multiple sibling calls to itself.
Diffstat (limited to 'scratch/facebook/interview-cake/nth-fibonacci.py')
-rw-r--r--scratch/facebook/interview-cake/nth-fibonacci.py6
1 files changed, 6 insertions, 0 deletions
diff --git a/scratch/facebook/interview-cake/nth-fibonacci.py b/scratch/facebook/interview-cake/nth-fibonacci.py
new file mode 100644
index 000000000000..4629798cf711
--- /dev/null
+++ b/scratch/facebook/interview-cake/nth-fibonacci.py
@@ -0,0 +1,6 @@
+def fib(n):
+    cache = (0, 1)
+    for _ in range(n):
+        a, b = cache
+        cache = (b, a + b)
+    return cache[0]