> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Fibonacci Number Python Solution with Tests

> Tested Python solution for LeetCode 509 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 509, [Easy](/catalog/easy). Topics: [Math](/catalog/topics/math), [Dynamic Programming](/catalog/topics/dynamic-programming), [Recursion](/catalog/topics/recursion), [Memoization](/catalog/topics/memoization). [View on LeetCode](https://leetcode.com/problems/fibonacci-number/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 509   # by problem number
lcpy gen -s fibonacci_number   # by problem name
```

## Problem

The \<b>Fibonacci numbers\</b>, commonly denoted \<code>F(n)\</code> form a sequence, called the \<b>Fibonacci sequence\</b>, such that each number is the sum of the two preceding ones, starting from \<code>0\</code> and \<code>1\</code>. That is,

\<pre>
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
\</pre>

\<p>Given \<code>n\</code>, calculate \<code>F(n)\</code>.\</p>

### Examples

```
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
```

```
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
```

```
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
```

### Constraints

* 0 \<= n \<= 30

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/fibonacci_number/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/fibonacci_number/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def fib(self, n: int) -> int:
        prev, curr = 0, 1
        for _ in range(n):
            prev, curr = curr, prev + curr
        return prev
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.