def fib(n):
"""
Calculates the nth Fibonacci number with amortized constant runtime and linear memory.
Args:
n: The index of the desired Fibonacci number (non-negative integer).
Returns:
The nth Fibonacci number.
"""
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
Explanation:
Amortized Constant Runtime: The loop iterates n-1 times. However, each iteration performs a fixed number of operations (addition and assignment). Therefore, the runtime is O(n). However, if you consider a sequence of n calls to fib(n) for increasing n, the amortized cost per call is constant. This is because the work done in each call is proportional to the difference between consecutive n values. In practice, for a single call, it's linear.
Linear Memory: The function uses a fixed number of variables (a, b, _, n) regardless of the input n. Therefore, the memory usage is O(1) or constant. The memory doesn't grow with the input size.
Iterative Approach: The code uses an iterative approach instead of recursion. Recursive Fibonacci implementations are notoriously inefficient due to repeated calculations of the same Fibonacci numbers.
Tuple Assignment: The line a, b = b, a + b is a concise way to update a and b simultaneously. It's equivalent to:
python
temp = b
b = a + b
a = temp
Base Cases: The if n <= 1: handles the base cases for F(0) = 0 and F(1) = 1.
How it works:
The code maintains two variables, a and b, which represent the two most recent Fibonacci numbers. It iterates from 2 up to n, calculating the next Fibonacci number by adding a and b, and then updating a and b to prepare for the next iteration. Finally, it returns the value of b, which will be the nth Fibonacci number.