← Back to libraryQuestion 70 of 273
⌨️Java CodingBeginner

Generate the Fibonacci Series

📌 Definition:

Produce the sequence where each number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8...

📖 Detailed Explanation:

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.

💻 Solutions:
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 precision
🔑 Key Points:
  • Iterative two variables: O(n) time, O(1) space
  • Naive recursion is O(2^n)
  • Memoization brings recursion to O(n)
  • Overflow: use BigInteger / big int for large n
🌍 Real-World Example:

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

🎯 Scenario-Based Interview Question:

A candidate's naive recursive fib hangs for fib(50). Explain and give two fixes.