AlgoInsight

DSA problem

Fibonacci Number

Easy1-D DPPattern: 1-D DPtop600AmazonMicrosoftGoogleAppleBloomberg

The Fibonacci sequence is defined by the recurrence F(n) = F(n - 1) + F(n - 2) with base cases F(0) = 0 and F(1) = 1. Given a non-negative integer n, return F(n).

A direct top-down recursive translation of the definition is correct but disastrously slow: it recomputes the same subproblems exponentially many times, giving O(2^n) calls. A classic case of "the algorithm is right, but it does the same work over and over."

Memoization caches each F(k) the first time it is computed, dropping the runtime to O(n). Even better is the bottom-up tabulation: start from the base cases and build forward, computing each F(i) exactly once in a simple loop.

The optimal approach observes that at every step the only inputs needed are the previous two values. So we keep two rolling variables a and b and update them with a, b = b, a + b for n iterations. This drops the space from O(n) to O(1) while retaining O(n) time, which is the canonical "bottom-up rolling-variable" 1-D DP pattern.

Examples

Example 1
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dp1d-dpmathrecursion

Browse all DSA problems