DP - 1D · Easy
LeetCode 1137: N-th Tribonacci Number — solution
Bottom-up DP with three rolling variables: each term is the sum of the previous three. O(n) time and O(1) space.
Problem in plain words
The Tribonacci sequence starts with 0, 1, 1, and every later term is the sum of the three terms just before it. Given n (at most 37), return term number n, counting from 0.
So the sequence goes 0, 1, 1, 2, 4, 7, 13, 24, and the answer for n = 6 is 13.
Intuition
This is Fibonacci with one more term in the sum. A naive recursion recomputes the same terms an exponential number of times, but each term only depends on the three before it, so we can build the sequence from the bottom up and keep only a sliding window of three values. The same idea is animated in the bottom-up Fibonacci DP lesson.
Approach
- State:
T(i)is the i-th Tribonacci number. - Recurrence:
T(i) = T(i - 1) + T(i - 2) + T(i - 3). - Base cases:
T(0) = 0,T(1) = 1,T(2) = 1. Return them directly whenn < 3. - Order: compute from
i = 3up ton, holding the last three values ina,b,cand shifting them after each step.
Dry run
Input: n = 5. Start with a = 0, b = 1, c = 1.
| i | a + b + c | New (a, b, c) |
|---|---|---|
| 3 | 0 + 1 + 1 = 2 | (1, 1, 2) |
| 4 | 1 + 1 + 2 = 4 | (1, 2, 4) |
| 5 | 1 + 2 + 4 = 7 | (2, 4, 7) |
The answer is c = 7.
Java solution
class Solution {
public int tribonacci(int n) {
if (n == 0) return 0;
if (n < 3) return 1;
int a = 0, b = 1, c = 1;
for (int i = 3; i <= n; i++) {
int next = a + b + c;
a = b;
b = c;
c = next;
}
return c;
}
}Python solution
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n < 3:
return 1
a, b, c = 0, 1, 1
for _ in range(3, n + 1):
a, b, c = b, c, a + b + c
return cComplexity
| Measure | Cost | Why |
|---|---|---|
| Time | O(n) | One addition per term from 3 to n. |
| Space | O(1) | Only the last three terms are stored. |
Edge cases and common mistakes
- n = 0, 1, 2: handle these before the loop; returning
cforn = 0would wrongly give 1. - Overflow: the constraint
n <= 37keeps the answer under 2^31, sointis safe. For largernyou would needlongor a modulus. - Plain recursion:
T(n-1) + T(n-2) + T(n-3)without memoization is roughly O(1.84^n) and times out well before n = 37 in some languages. - Shifting in the wrong order: in Java, compute
nextfirst, then shifta,b,c; overwritingcfirst loses a value.
›How does memoization compare?
Top-down recursion with a cache is also O(n) time but uses O(n) space for the cache and the call stack. See the memoized Fibonacci lesson for that style.
