Back to the 100
Problem 010Dynamic Programming
Easy

Fibonacci Number

010

Return the nth Fibonacci number where F(0) = 0 and F(1) = 1.

EXAMPLES

Example 1
Input
{
  "n": 4
}

Output
3

FUNCTION SHAPE

n: intint
SOLUTION NOTE

This is the definition of DP! Once you have the recurrence relation and base cases, the code writes itself. The hard part is discovering the correct recurrence.

Reveal reference solution +
pythonREFERENCE
def fib(self, n: int) -> int:
    @cache
    def dp(n):
        if n in [0, 1]: return n
        return dp(n-1) + dp(n-2)
    return dp(n)
TimeO(n)
SpaceO(n)
Open on LeetCode
00:00
5 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.