Fibonacci Number

Iterative two-variable rolling — O(1) space.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
dp math recursion

Problem#

F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) for n >= 2. Return F(n).

Examples#

  • n=21; n=32; n=43.

Constraints#

  • 0 <= n <= 30.

Approach#

Iterative two-variable rolling.

Solution#

Fibonacci Number
class Solution {
public:
int fib(int n) {
if (n < 2) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; ++i) {
int c = a + b;
a = b;
b = c;
}
return b;
}
};

Editorial#

The naive recursive O(2^n) is the textbook example of overlapping subproblems. Iterating bottom-up with two rolling values is the canonical O(n) time, O(1) space form. Closed-form via matrix exponentiation gets O(log n) if needed.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.