Problem Description
Compute the n-th Tribonacci number where the sequence starts with T0 = 0, T1 = 1, T2 = 1, and for n >= 0, Tn+3 = Tn + Tn+1 + Tn+2.
Key Insights
- The Tribonacci sequence is similar to Fibonacci but sums the last three numbers instead of two.
- Base cases are provided for n = 0, 1, 2.
- The problem can be solved iteratively using dynamic programming with constant space by updating three variables.
- Given the constraints, an iterative solution is optimal.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
We use an iterative dynamic programming approach. For n less than or equal to 2, we directly return the base cases. For larger n, we maintain three variables corresponding to Tn-3, Tn-2, and Tn-1. In each iteration, we compute the current Tribonacci number as the sum of these three. We then update the variables accordingly, shifting them forward. This approach computes the result in O(n) time and uses O(1) space.