SDE & MLE Prep

1137. N-th Tribonacci Number

Problem

The Tribonacci sequence is T₀ = 0, T₁ = 1, T₂ = 1 and Tₙ₊₃ = Tₙ + Tₙ₊₁ + Tₙ₊₂. Return Tₙ.

Example: n = 4 → 4; n = 25 → 1389537

Constraints: n ≤ 37.

Fibonacci with three terms: keep a rolling window (a, b, c) and slide it n times.

Complexity: O(n) time, O(1) space.

class Solution:
    def tribonacci(self, n: int) -> int:
        a, b, c = 0, 1, 1
        for _ in range(n):
            a, b, c = b, c, a + b + c
        return a