◀ THE GRIND — 1-D DYNAMIC PROGRAMMING

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.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

EX 01
n = 0
0
SEED VALUE T0
EX 02
n = 1
1
SEED VALUE T1
EX 03
n = 2
1
SEED VALUE T2
THE HINTS — TAKE ONLY WHAT YOU NEED
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.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE TRIPLE ROLLPATTERN · ROLLING TRIPLEn = 7 · sequence seeded 0, 1, 1
0
1
1
STEP 1

Seed the sequence with its three starting terms: T0 = 0, T1 = 1, T2 = 1.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/n-th-tribonacci-number.pyRACE PACE
LANG ▸
PACE ▸
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 c
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 10 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED