Sub topic 10
Bottom-Up Fibonacci with a Loop
This chapter assumes you have read the chapters on naive recursive Fibonacci and memoization. You should be comfortable with Python functions, for loops, tuple assignment, and Big-O notation. We use the definition F(0) = 0, F(1) = 1, and F(n) = F(n−1) + F(n−2) for n ≥ 2.
Memoization fixed the exponential blow-up of naive Fibonacci by caching results. It still starts at the top, asking for F(n) and recursing down until it reaches the base cases. Bottom-up iteration turns that around. It starts at the base cases and works upward, computing each value only after the values it depends on are ready. Recursion is no longer needed, so nothing builds up on the call stack and no cache is required.
The Dependency Order
Every Fibonacci value depends only on the two values just below it. If you compute F(0), F(1), F(2), ... in that order, both inputs are always available when you reach F(i). That order is a topological order of the dependency graph: each node comes after everything it depends on.
Memoization discovers this order at run time by following recursive calls. The bottom-up approach writes the order down directly as a loop.
Version 1: Fill a Table
The most direct translation stores every value in a list. Entry i holds F(i).
def fib_table(n):
if n < 0:
raise ValueError("n must be non-negative")
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(fib_table(10)) # 55
print(fib_table(0)) # 0The loop runs n − 1 times and does one addition per pass, so the time is O(n) additions. The table holds n + 1 entries, so the extra space is O(n). That matches the memoized version without the recursion.
The early return for n < 2 matters. Without it, fib_table(0) would build a one-element list and then fail on table[1] = 1 with an IndexError.
Version 2: Keep Only Two Values
Look at the loop body again. Computing table[i] reads only table[i - 1] and table[i - 2]. Once you have moved past an entry, nothing reads it again. So you can drop the list and keep a sliding window of two numbers.
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_iter(10)) # 55This version runs in O(n) time with O(1) extra space, counting each integer as one unit. It handles n = 0 without a special case: the loop body never runs and the function returns a = 0.
Tracing the Window
Here is the state after each iteration for fib_iter(6):
| Iterations completed | a | b |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 3 | 5 |
| 5 | 5 | 8 |
| 6 | 8 | 13 |
The function returns a = 8, which is F(6). Notice that b is always one step ahead: the loop computes F(7) = 13 even though nobody asked for it. That extra addition costs almost nothing, and it keeps the code free of special cases.
Why It Is Correct: The Loop Invariant
The induction argument from earlier in the tutorial applies to loops as well, in the form of a loop invariant. A loop invariant is a statement that is true before the loop starts and stays true after every iteration.
The invariant here is: after k iterations, a == F(k) and b == F(k + 1).
- Base: before any iteration, k = 0,
a = 0 = F(0)andb = 1 = F(1). - Step: suppose
a = F(k)andb = F(k + 1). The assignment sets the newatoF(k + 1)and the newbtoF(k) + F(k + 1) = F(k + 2). The invariant holds for k + 1. - Termination: the loop runs exactly n times, so at the end
a = F(n).
This is the same proof you would write for the recursive version, with "number of iterations" in place of "size of the argument."
Common Errors
Splitting the Simultaneous Assignment
Python's a, b = b, a + b evaluates the whole right side before it assigns anything. If you split it into two statements, the second line reads the new a instead of the old one:
def fib_broken(n):
a, b = 0, 1
for _ in range(n):
a = b
b = a + b # a has already changed: this computes b + b
return a
print([fib_broken(i) for i in range(8)]) # [0, 1, 2, 4, 8, 16, 32, 64]
print([fib_iter(i) for i in range(8)]) # [0, 1, 1, 2, 3, 5, 8, 13]The broken version doubles b every time and produces powers of two. In languages without tuple assignment, use a temporary variable:
def fib_temp(n):
a, b = 0, 1
for _ in range(n):
nxt = a + b
a = b
b = nxt
return a
print(fib_temp(10)) # 55Off-by-One Loop Bounds
Writing range(n - 1) or returning b instead of a shifts the result by one index. For example, returning b gives F(n + 1). The invariant tells you which variable to return. When you change the loop bounds, re-check the invariant at k = 0 and at k = n rather than guessing.
Ignoring Negative Input
fib_iter(-3) returns 0, because range(-3) is empty. That is silently wrong. If callers might pass negative values, validate the input the way fib_table does.
Comparing Top-Down and Bottom-Up
| Property | Naive recursion | Memoized (top-down) | Bottom-up, table | Bottom-up, two variables |
|---|---|---|---|---|
| Additions | about F(n) (exponential) | O(n) | O(n) | O(n) |
| Extra space | O(n) stack | O(n) cache + O(n) stack | O(n) list | O(1) |
| Hits recursion limit | Yes, for large n | Yes, on a cold cache | No | No |
| Computes only needed values | Yes (repeatedly) | Yes | No, computes all below n | No, computes all below n |
The last row is where top-down sometimes wins. In problems where only a sparse subset of subproblems is needed, memoization computes just those, while a bottom-up loop fills in everything. Fibonacci needs every smaller value anyway, so bottom-up has no downside here.
The recursion limit difference is easy to demonstrate:
import sys
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# The two methods agree on small inputs.
assert all(fib_memo(i) == fib_iter(i) for i in range(300))
fib_memo.cache_clear()
print(sys.getrecursionlimit()) # usually 1000
try:
fib_memo(5000)
except RecursionError:
print("fib_memo(5000) hit the recursion limit")
print(len(str(fib_iter(5000)))) # 1045 digitsThe Hidden Cost of Big Integers
"O(n) time" assumes each addition takes constant time. Python integers have arbitrary precision, and F(n) grows like φⁿ/√5, where φ ≈ 1.618. So F(n) has about 0.694·n bits. For large n, each addition costs time proportional to the number of bits, and the total work becomes roughly O(n²) bit operations. For n in the thousands this is fast in practice. For n in the millions it becomes noticeable, and faster methods such as matrix exponentiation or the fast-doubling identities apply. Those reuse the exponentiation-by-squaring idea covered later in this tutorial.
Generating the Whole Sequence
The two-variable loop produces every Fibonacci number along the way, so it also works as a generator when you need the sequence instead of a single value:
from itertools import islice
def fib_sequence():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fib_sequence(), 10))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Producing the first k values costs O(k) additions in total. Calling fib_iter(i) separately for each i would cost O(k²).
Exercises
Exercise
Rewrite fib_iter so it returns b instead of a, adjusting the loop bound so the function still returns F(n) for every n ≥ 1. What happens at n = 0, and how would you fix it?
Show answer
Use for _ in range(n - 1) and return b. After n − 1 iterations the invariant gives b = F(n). At n = 0, range(-1) is empty and the function returns b = 1, which is wrong because F(0) = 0. Add if n == 0: return 0 before the loop. This edge case is why the original version, which returns a after n iterations, is cleaner.
Exercise
The Lucas numbers follow the same recurrence as Fibonacci, L(n) = L(n−1) + L(n−2), but start with L(0) = 2 and L(1) = 1. Write a bottom-up function lucas(n) with O(1) extra space and state its loop invariant.
Show answer
def lucas(n): then a, b = 2, 1, then for _ in range(n): a, b = b, a + b, then return a. Invariant: after k iterations, a = L(k) and b = L(k+1). For example, lucas(5) returns 11 (sequence 2, 1, 3, 4, 7, 11). Only the starting pair changes, because the starting pair encodes the base cases.
Exercise
A colleague says that fibtable and fibiter both run in O(n) time, so there is no reason to prefer one. Give two concrete reasons to prefer fib_iter, and one situation where keeping the table is useful.
Show answer
fib_iter uses O(1) extra space instead of an O(n) list, and it needs no special case for n = 0 or n = 1. The table is useful when you will answer many queries for different indices up to n: build it once in O(n), then answer each query by lookup in O(1).