Interview challenge · easy · math, loops, dynamic-programming
Fibonacci Series
The challenge
Print the first n numbers of the Fibonacci series. It starts with 0 and 1, and every next number is the sum of the two before it.
Example
n = 10 -> 0 1 1 2 3 5 8 13 21 34Idea: the textbook recursion fib(n) = fib(n-1) + fib(n-2) computes the same values again and again and takes exponential time. A loop that keeps only the last two numbers prints the whole series in O(n) time and O(1) space: print a, then move the pair one step with a, b = b, a + b. The numbers grow fast, so the C version uses long.
The solution
# Fibonacci Series - ayotl.dev
def fibonacci(n):
out = []
a, b = 0, 1
# keep only the last two numbers
for _ in range(n):
out.append(a)
a, b = b, a + b
return out
print(*fibonacci(10))
print(*fibonacci(15))
$ python3 fibonacci_series.py
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377