The problem at hand is about calculating the Fibonacci numbers, which is a classic problem. Given an integer n
, we need to compute the n-th
Fibonacci number. The Fibonacci sequence is defined by the following recurrence relation:
n
?
A: The constraints typically ensure that n
is a manageable size; for LeetCode, it’s usually within the range [0, 30].n
possible in the input?
A: No, n
is guaranteed to be a non-negative integer.Here is an implementation using the iterative approach:
def fib(n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
# Initial base values for the sequence
a, b = 0, 1
# Iteratively compute the nth Fibonacci number
for _ in range(2, n + 1):
a, b = b, a + b
return b
# Example Usage
print(fib(0)) # Output: 0
print(fib(1)) # Output: 1
print(fib(2)) # Output: 1
print(fib(3)) # Output: 2
print(fib(10)) # Output: 55
n
, so the time complexity is linear with respect to n
.a
and b
) regardless of the input size.This approach ensures that we compute the Fibonacci number efficiently with minimal space usage.
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?