Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-010

Fibonacci Number

Problem

Return the n-th Fibonacci number with F(0) = 0 and F(1) = 1, computed iteratively in O(n) time and O(1) space.

The sequence satisfies F(n) = F(n-1) + F(n-2) for n >= 2. Assume n is a non-negative integer.

Hint

Keep only the last two values and roll them forward n times.

Test cases

case 1
in: [0]
expected: 0
case 2
in: [1]
expected: 1
case 3
in: [10]
expected: 55
case 4
in: [30]
expected: 832040
case 5
in: [45]
expected: 1134903170
Starter codePython
def fibonacci(n):
    # Your code here
    pass

5 test cases · run your code against them in the editor