N-th Tribonacci Number
The drill: A sibling of Fibonacci where each term sums the three terms before it instead of two, seeded 0, 1, 1. Compute the n-th term of that sequence.
A sequence starts with the three seed values 0, 1, and 1, and every term after that is the sum of the three terms immediately before it — the same idea as Fibonacci, one term wider.
The task is to compute a single term of that sequence at a chosen position, counting the very first seed value as position zero.
- position n is a small non-negative integer
- sequence is seeded 0, 1, 1 at positions 0, 1, 2
- each term is the sum of the three terms directly before it
- answer fits within a standard 32-bit integer range
HINT 1 THE NUDGE
The direct recursive definition — sum the previous three calls — recomputes the same small n's an exploding number of times. Which values does the very next term actually need?
HINT 2 THE STRUCTURE
Only the last three terms ever matter to produce the next one. Once a term is more than three steps behind, it's dead weight.
HINT 3 ONE STEP FROM THE ANSWER
Slide three variables forward: the new term is their sum, and the oldest of the three gets dropped. Seed with T0 = 0, T1 = 1, T2 = 1 and roll forward to n.
Seed the sequence with its three starting terms: T0 = 0, T1 = 1, T2 = 1.
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n == 1 or n == 2:
return 1
a, b, c = 0, 1, 1 # T0, T1, T2
for _ in range(3, n + 1):
a, b, c = b, c, a + b + c
return cclass Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n == 1 or n == 2:
return 1
return self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3)class Solution {
public int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
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;
}
}class Solution {
public int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
return tribonacci(n - 1) + tribonacci(n - 2) + tribonacci(n - 3);
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED