Leetcode 509. Fibonacci Number Problem Statement:
The Fibonacci numbers, commonly denoted F(n), form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
Given n
, calculate F(n)
.
Clarifying Questions:
n
that we need to handle?
Assuming the value of n
can be large (e.g., up to 30) and additional data structures are allowed, we’ll go for an iterative approach which is both time efficient and space efficient.
Strategy:
n == 0
.n == 1
.a
and b
).n
, computing the current Fibonacci number by summing the previous two.Code:
#include <iostream>
int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int a = 0, b = 1;
for (int i = 2; i <= n; ++i) {
int temp = a + b;
a = b;
b = temp;
}
return b;
}
int main() {
int n = 10; // Example input
std::cout << "Fibonacci number at position " << n << " is: " << fib(n) << std::endl;
return 0;
}
Time Complexity:
n
, so the time complexity is linear with respect to the input n
.This code is efficient for calculating Fibonacci numbers even for relatively large values of n
and avoids the pitfalls of stack overflow or excessive recomputation that a naive recursive solution might encounter.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?