N-th Tribonacci Number Problem
Description
LeetCode Problem 1137.
The Tribonacci sequence T_n is defined as follows:
T_0 = 0, T_1 = 1, T_2 = 1, and T_(n+3) = T_n + T_(n+1) + T_(n+2) for n >= 0.
Given n, return the value of T_n.
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
Constraints:
0 <= n <= 37- The answer is guaranteed to fit within a 32-bit integer, ie.
answer <= 2^31 - 1.
Solution
Approach: Iterate with Three Variables
Each term only depends on the three before it, so there is no need to store the whole sequence. Keep three variables a, b, c holding T(i), T(i+1) and T(i+2), starting at i = 0 with 0, 1, 1.
One step moves the window forward: the new values are b, c and a + b + c. After n steps, a holds T(n). This also covers n = 0, 1 and 2 without special cases, because the loop runs fewer times and a already has the right starting value.
The last steps compute c = T(n+2), which for n = 37 is larger than a 32-bit integer can hold even though the answer T(37) fits. The Java and C++ versions therefore use 64-bit variables.
Complexity: O(n) time and O(1) extra space.
class Solution:
def tribonacci(self, n: int) -> int:
a, b, c = 0, 1, 1 # T(i), T(i+1), T(i+2), starting at i = 0
for _ in range(n):
a, b, c = b, c, a + b + c
return a