Wasted effort clearly much of the effort in computing fib(n) is wasted for almost all values of n, since much information is being computed redundantly
Q: if 300 million calls are made for n=40, about how many times is fib(n) computed, on average, for each n between 0 and 40?
Lecture #2: Two Sample Problems in Analysis
Improving the Fibonacci computation
Wasted effort
Filling in an array of results imagine that we wish to fill an array F[] with Fibonacci values, rather than just return a single result; now we can compute fib(n) by filling in the array from left to right, and then pluck out the last value
Q: what is the asymptotic running time of this algorithm for fib(n)?
Lecture #2: Two Sample Problems in Analysis
Improving the Fibonacci computation
Wasted effort
Filling in an array of results
Saving space with the sliding window rather than filling in the whole array, we can keep three local variables to maintain the values of the current and last two values, and thus simulate a "sliding window" of width three moving across the array
Q: what is the asymptotic space usage of this algorithm compared to the last one?
Lecture #2: Two Sample Problems in Analysis
Improving the Fibonacci computation
Wasted effort
Filling in an array of results
Saving space with the sliding window
Caching the results (memoized version) on the other hand, it may be useful to use the array after all: if we will be serving requests for fib(n) for many values of n at different times, we can keep the array as computed so far, and then just look up the values if they have already been computed
Q: what are the asymptotic time and space usage this algorithm?