Magicsheet logo

N-th Tribonacci Number

Easy
38.7%
Updated 6/1/2025

N-th Tribonacci Number

What is this problem about?

The N-th Tribonacci Number problem asks you to compute the n-th number in the Tribonacci sequence, where each number is the sum of the three preceding ones: T(0)=0, T(1)=1, T(2)=1, T(n)=T(n-1)+T(n-2)+T(n-3). This N-th Tribonacci Number coding problem is a natural extension of Fibonacci and tests iterative DP with a rolling window of three values.

Why is this asked in interviews?

Meta, Amazon, Google, and Bloomberg ask this to test DP fundamentals and the ability to generalize sequence recurrences. It's a warm-up problem that validates understanding of memoization and iterative space optimization. The math, memoization, and dynamic programming interview pattern is directly demonstrated.

Algorithmic pattern used

Iterative DP with rolling window. Maintain three variables a, b, c representing T(n-3), T(n-2), T(n-1). For each step: next = a + b + c, then shift: a=b, b=c, c=next. This achieves O(1) space and O(n) time. For top-down: use memoization with a hashmap or array.

Example explanation

Compute T(6): T(0)=0, T(1)=1, T(2)=1, T(3)=2, T(4)=4, T(5)=7, T(6)=13. Iterative: a=0,b=1,c=1. Step: next=2, shift → a=1,b=1,c=2. next=4 → a=1,b=2,c=4. next=7 → a=2,b=4,c=7. next=13 → T(6) = 13.

Common mistakes candidates make

  • Using recursive Fibonacci code with three recursive calls (exponential time without memoization).
  • Incorrect base cases (T(0)=0, T(1)=1, T(2)=1 — note T(1)=T(2)=1).
  • Off-by-one when shifting the rolling window.
  • Not handling n=0, n=1, n=2 as special cases before the loop.

Interview preparation tip

After mastering Fibonacci with O(1) space, extending to Tribonacci is straightforward — just add a third variable. The rolling window pattern generalizes to any k-step recurrence: maintain k variables, compute the next as sum of all k, shift. Practice this generalization for k=2 (Fibonacci), k=3 (Tribonacci), and k=4 to build fluency. Matrix exponentiation can compute T(n) in O(log n) — worth mentioning as an advanced optimization.

Similar Questions