Iterate from the three base values while retaining only the latest three terms.
Complexity
O(n) time and O(1) space.
Compute the sequence where each term is the sum of the previous three terms.
Iterate from the three base values while retaining only the latest three terms.
O(n) time and O(1) space.
package main
func tribonacci(n int) int {
if n == 0 {
return 0
}
first, second, third := 0, 1, 1
for index := 3; index <= n; index++ {
first, second, third = second, third, first+second+third
}
return third
}
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0: return 0
first, second, third = 0, 1, 1
for _ in range(3, n + 1): first, second, third = second, third, first + second + third
return third
function tribonacci(n: number): number {
if (n === 0) return 0; if (n < 3) return 1;
let first = 0; let second = 1; let third = 1;
for (let index = 3; index <= n; index += 1) [first, second, third] = [second, third, first + second + third];
return third;
}