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.
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.
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.