LeetCode 0509. Fibonacci Number Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0509. Fibonacci Number

Description

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.

Given n, calculate F(n).

 

Example 1:

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

Example 2:

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

Example 3:

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

 

Constraints:

  • 0 <= n <= 30

Solutions

Solution 1: Recurrence

We define two variables a and b, initially a = 0 and b = 1.

Next, we perform n iterations. In each iteration, we update the values of a and b to b and a + b, respectively.

Finally, we return a.

The time complexity is O(n), where n is the given integer. The space complexity is O(1).

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

Solution 2: Matrix Exponentiation

We define Fib(n) as a 1 × 2 matrix \begin{bmatrix} F_n & F_{n - 1} \end{bmatrix}, where F_n and F_{n - 1} are the n-th and (n - 1)-th Fibonacci numbers, respectively.

We want to derive Fib(n) from Fib(n - 1) = \begin{bmatrix} F_{n - 1} & F_{n - 2} \end{bmatrix}. In other words, we need a matrix base such that Fib(n - 1) × base = Fib(n), i.e.:

$$ \begin{bmatrix} F_{n - 1} & F_{n - 2} \end{bmatrix} \times \textit{base} = \begin{bmatrix} F_n & F_{n - 1} \end{bmatrix} $$

Since F_n = F_{n - 1} + F_{n - 2}, the first column of the matrix base is:

$$ \begin{bmatrix} 1 \ 1 \end{bmatrix} $$

The second column is:

$$ \begin{bmatrix} 1 \ 0 \end{bmatrix} $$

Thus, we have:

$$ \begin{bmatrix} F_{n - 1} & F_{n - 2} \end{bmatrix} \times \begin{bmatrix}1 & 1 \ 1 & 0\end{bmatrix} = \begin{bmatrix} F_n & F_{n - 1} \end{bmatrix} $$

We define the initial matrix res = \begin{bmatrix} 1 & 0 \end{bmatrix}, then F_n is equal to the second element of the first row of the result matrix obtained by multiplying res with base^{n}. We can solve this using matrix exponentiation.

The time complexity is O(log n), and the space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScript
import numpy as np class Solution: def fib(self, n: int) -> int: factor = np.asmatrix([(1, 1), (1, 0)], np.dtype("O")) res = np.asmatrix([(1, 0)], np.dtype("O")) while n: if n & 1: res = res * factor factor = factor * factor n >>= 1 return res[0, 1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !