Solve InterviewCake's compute nth Fibonacci

While the "Dynamic programming and recursion" section hosts this problem, the
optimal solution does not use recursion. Many cite the Fibonacci problem as a
quintessential dynamic programming question. I assume these people expect an
answer like:

```python
def fib(n):
  cache = {0: 0, 1: 1}
  def do_fib(n):
    if n in cache:
      return cache[n]
    else:
      cache[n - 1] = do_fib(n - 1)
      cache[n - 2] = do_fib(n - 2)
      return cache[n - 1] + cache[n - 2]
  return do_fib(n)
```

The cache turns the runtime of the classic Fibonacci solution...

```python
def fib(n):
  if n in {0, 1}:
    return n
  return fib(n - 1) + fib(n - 2)
```

... from O(2^n) to a O(n). But both the cache itself and the additional stacks
that the runtime allocates for each recursive call create an O(n) space
complexity.

InterviewCake wants the answer to be solved in O(n) time with O(1)
space. To achieve this, instead of solving fib(n) from the top-down, we solve it
from the bottom-up.

I found this problem to be satisfying to solve.
This commit is contained in:
William Carroll 2020-03-30 14:14:02 +01:00
parent 7e41aba8b7
commit 8d36c6d00f
2 changed files with 73 additions and 1 deletions

View file

@ -29,7 +29,7 @@
** DONE Find Repeat, Space Edition BEAST MODE
* Dynamic programming and recursion
** DONE Recursive String Permutations
** TODO Compute nth Fibonacci Number
** DONE Compute nth Fibonacci Number
** TODO Making Change
** TODO The Cake Thief
** DONE Balanced Binary Tree