Produce the sequence where each number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8...
Iterate keeping two variables (prev, curr) and update n times — O(n) time, O(1) space, the preferred answer. Naive recursion is O(2^n) because it recomputes overlapping subproblems. Values overflow 32/64-bit ints quickly, so use big integers for large n.
public static long fib(int n) {
if (n < 2) return n;
long prev = 0, curr = 1;
for (int i = 2; i <= n; i++) {
long next = prev + curr; prev = curr; curr = next;
}
return curr;
}function fib(n) {
if (n < 2) return n;
let prev = 0n, curr = 1n; // BigInt avoids overflow
for (let i = 2; i <= n; i++) [prev, curr] = [curr, prev + curr];
return curr;
}def fib(n):
if n < 2:
return n
prev, curr = 0, 1
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return curr # Python ints are arbitrary precisionFibonacci is a vehicle for the exponential-vs-linear lesson — spotting hidden blow-ups is the same skill as catching an accidental O(2^n) in code.
A candidate's naive recursive fib hangs for fib(50). Explain and give two fixes.