Fibonacci Number — LeetCode 509 Python Solution

EasyRecursionMemoizationMathDynamic Programming
Problem
#509
Reading time
2 min

The problem

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, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1.

Example

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Python solution

Python
class Solution:
    def fib(self, n: int) -> int:
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a

Complexity

MeasureComplexity
TimeO(n), where n is the given integer
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 509. Fibonacci Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 509. Fibonacci Number?
LeetCode 509. Fibonacci Number is rated Easy on LeetCode.
What is the time complexity of LeetCode 509. Fibonacci Number?
The Python solution on this page runs in O(n), where n is the given integer.
What is the space complexity of LeetCode 509. Fibonacci Number?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 509. Fibonacci Number cover?
LeetCode 509. Fibonacci Number is tagged Recursion, Memoization, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview