Skip to main content

Fibonacci Numbers

EasyPremium

Write a function fib(n) that returns the nth Fibonacci number. The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2) with F(0) = 1 and F(1) = 1, which produces the following pattern:

1, 1, 2, 3, 5, 8, 13 ...

Examples

Python
fib(0) # => 1 fib(1) # => 1 fib(2) # => 2 fib(3) # => 3 ... fib(10) # => 89 fib(20) # => 10946

The Fibonacci sequence is defined recursively since it refers to itself.

We can start with a recursive implementation and optimize it.

Each call to F(n) has two subproblems: F(n-1) and F(n-2). Can we memoize these calculations?

Does your solution work in O(n) time?