Fibonacci Number — LeetCode 509 Python Solution
- Problem
- #509
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
class Solution:
def fib(self, n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return aComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the given integer |
| Space | O(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.