Fibonacci Number solution explained

To compute the n-th Fibonacci number, keep the last two values and step forward n times: (prev, cur) becomes (cur, prev + cur), starting from (0, 1). That is O(n) time and O(1) memory, and it is the answer most interviewers expect after you explain why plain recursion is exponential. For very large n, fast doubling uses F(2m) = F(m) * (2F(m + 1) - F(m)) and F(2m + 1) = F(m)^2 + F(m + 1)^2 to get there in O(log n) arithmetic steps.

By Published 7 min read

The problem in plain words

The Fibonacci sequence starts 0, 1, and every later term is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and so on. Given a non-negative integer n, return the term at position n, counting from 0. The problem usually keeps n small enough that the answer fits in a 32-bit integer, which makes it a question about approach rather than arithmetic. Interviewers use it to open a conversation about recursion, repeated work and dynamic programming.

Values computed with the code on this page
nF(n)Note
00Base case
11Base case
12144The only Fibonacci square above 1, a nice trivia fact
206,765
30832,040Naive recursion already makes 2,692,537 calls
788,944,394,323,791,464The last term a JavaScript number holds exactly
100,000a 20,899-digit numberPython handles it; fast doubling helps
Values computed with the code on this page. Scroll sideways on a small screen.

What the interviewer listens for

The question is a vehicle for one idea: the naive recursion solves the same subproblems over and over, and storing answers removes that waste. A strong answer names the exponential blowup, explains memoization (top-down) versus tabulation (bottom-up), shrinks the table to two variables, and states the complexity of each step. Mentioning the size of the numbers, and the faster method for huge n, shows range. Interviewers also notice whether you handle n = 0 and n = 1 without special-case clutter.

Common follow-ups

  • Return F(n) modulo a large prime. Take the remainder at every step, which keeps numbers small in any language; fast doubling works the same way.
  • Climbing stairs, one or two steps at a time. The number of ways follows the same recurrence, shifted by one.
  • Why not the closed-form formula? Binet's formula rounds phi^n / sqrt(5), which is exact in theory but uses floating point; in double precision it first gives a wrong answer at n = 71.
  • Tribonacci or a general k-term sum. Keep a window of the last k values.
  • Print the first n terms. The loop produces them in order, so collect them as you go.

First versions: recursion, then memoization

The definition translates straight into code: return n for 0 and 1, otherwise call yourself for n - 1 and n - 2. It is correct, and it is a good first sentence, but the call tree branches twice at every level and computes F(n - 2) once from F(n) and again inside F(n - 1). The number of calls is 2F(n + 1) - 1, so it grows roughly like 1.618^n: 242,785 calls for n = 25 and 2,692,537 for n = 30. Adding a dictionary of computed values, so each n is worked out once, reduces it to O(n) calls and O(n) memory.

@@fibonacci-number/slow.py@@
Python: plain recursion (exponential) and memoized recursion (linear).

The memoized version still recurses n levels deep. Python's default recursion limit of about 1,000 frames makes it fail with a RecursionError somewhere near n = 1,000 (it ran for 900 and failed for 1,200 in testing). That is a strong reason to switch to the bottom-up loop.

Expected version: bottom-up with two variables

Each term depends only on the two before it, so the table of all previous values is unnecessary. Start with prev = F(0) and cur = F(1), and step n times, replacing the pair with (cur, prev + cur). After n steps, prev holds F(n). This is the standard dynamic-programming move of compressing a table to the slice the recurrence actually reads, and it is the answer that ends most interviews on this question.

@@fibonacci-number/fast.py@@
Python: iterative O(n), plus fast doubling with O(log n) recursive steps.

Fast doubling, the second function above, computes the pair (F(k), F(k + 1)) from the pair for k // 2 using the two identities in the opening paragraph, then shifts by one if k is odd. Each halving of k costs a few multiplications, so there are O(log n) steps. Be precise when you say this: the count of arithmetic operations is logarithmic, but when results have thousands of digits each multiplication gets more expensive, so the real running time is higher. Matrix exponentiation of [[1, 1], [1, 0]] gives the same bound and is the version some interviewers know by name.

In JavaScript, ordinary numbers are 64-bit floats with 53 bits of integer precision. F(78) still fits exactly; F(79) is larger than 2^53 and the iterative Number version first goes wrong there. Using BigInt avoids the problem at the cost of slower arithmetic.

@@fibonacci-number/fast.js@@
JavaScript: iterative with BigInt, exact for any n.

Cost of each approach

Counting arithmetic steps; very large results make each step slower
ApproachTimeExtra memoryNote
Plain recursionO(phi^n), about 1.618^nO(n) call stack2F(n + 1) - 1 calls
Memoized recursionO(n)O(n) table and stackHits Python's recursion limit near n = 1,000
Bottom-up with two variablesO(n)O(1)The usual expected answer
Fast doubling or matrix powerO(log n) stepsO(log n) stack, or O(1) if written iterativelyWorth it for huge n or with a modulus
Binet's formula in floating pointO(1)O(1)Wrong from n = 71 in double precision
Counting arithmetic steps; very large results make each step slower. Scroll sideways on a small screen.

Edge cases

  • n = 0 and n = 1, which the loop handles with zero and one step.
  • The largest n in the problem's range, to check the result type: a 32-bit signed integer holds up to F(46), a JavaScript number exactly up to F(78), a 64-bit signed integer up to F(92).
  • Negative n, which is outside the usual definition; say you would raise an error.
  • Repeated calls: if the function is called for many n, cache results across calls or precompute a table once.

Common slips

  • Returning cur instead of prev after the loop, which gives F(n + 1).
  • Writing prev = cur; cur = prev + cur as two separate statements, which doubles cur instead of adding the old prev. Use a tuple swap or a temporary.
  • Putting a mutable default argument such as seen={} in a Python memo function, which shares the cache across calls in surprising ways; the version here uses None.
  • Claiming O(1) for Binet's formula without mentioning that floating point breaks it.
  • Calling fast doubling O(log n) time without qualification when the numbers are huge.

How to explain it out loud

Fictional example

From the definition to two variables
Candidate
The direct recursion is correct but exponential: computing F of n calls F of n minus 2 twice, and it compounds. For n of 30 that's millions of calls.
Candidate
Each value only needs the previous two, so I'll loop from the bottom with two variables. Linear time, constant memory.
Candidate
If n could be enormous, or we wanted the answer modulo something, I'd use fast doubling for a logarithmic number of steps. And in JavaScript I'd use BigInt past the 78th term, where plain numbers lose precision.

Power of Two is another quick numeric warm-up that opens a discussion about representation. Counting Bits applies the same reuse-earlier-answers idea to bit counts. Fizz Buzz is the other classic first question, where structure matters more than speed. Count Primes is a further example of spending memory to save time.

Natively for practice

This question rewards a clear progression more than a clever trick. While practicing on Mac or Windows, Natively can read the question from a screenshot, step through the naive call tree with you, and ask the follow-ups about huge n or a modulus. With the transcript of the mock in front of you, it is easy to see whether you explained the move from recursion to the loop or skipped straight to it.

Questions people ask

What is the best way to compute the n-th Fibonacci number?

For interview-sized n, loop from the bottom with two variables, replacing (prev, cur) with (cur, prev + cur) n times. That is O(n) time and O(1) memory. For huge n, fast doubling needs O(log n) steps.

Why is recursive Fibonacci so slow?

Each call makes two more calls, and the same values are recomputed many times. Plain recursion makes 2F(n + 1) - 1 calls, which is 2,692,537 calls for n = 30.

What is the time complexity of memoized Fibonacci?

O(n) time and O(n) memory, because each value from 0 to n is computed once and stored. The recursion is also n levels deep, which can hit Python's default recursion limit near n = 1,000.

Can you compute Fibonacci numbers with Binet's formula?

In exact arithmetic yes, but with floating point the rounding error grows. In double precision, rounding phi^n / sqrt(5) first gives a wrong value at n = 71.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP