0
def fastfib(n, fib_dict = {0: 1, 1: 1}):
    if n not in fib_dict:
         fib_dict[n] = fastfib(n-1, fib_dict) + fastfib(n-2, fib_dict)
    return fib_dict[n]

I think the complexity here is n^2, but I am not sure.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
trap28
  • 97
  • 7

1 Answers1

1

Since you are filling a dictionary with n values, the lower bound is O(n). However, since you're only doing constant-time operations for each n, (Pythons dictionary lookup operation is O(1), though amortized), this algorithm should be O(n) (amortized). This technique of saving already computed values in a table is called memoization.

Tim
  • 2,123
  • 4
  • 27
  • 44