N-th Tribonacci Number (LeetCode 1137): Solution and Explanation

Easy
Math
Dynamic Programming
Memoization

The Tribonacci sequence starts with T(0) = 0, T(1) = 1 and T(2) = 1, and every later term is the sum of the three terms before it. Given n between 0 and 37, return T(n).

Intuition

The recurrence reads like code: T(n) = T(n - 1) + T(n - 2) + T(n - 3). Written as plain recursion, each call fans out into three more, so the call tree grows roughly like 1.84^n and recomputes the same small terms over and over.

If you compute the terms from the bottom instead, T(3) first, then T(4), and so on, every term you need is already known when you reach it. Nothing is computed twice.

Each new term reads exactly the three terms right before it. Anything older is never read again, so there is no reason to keep a whole array.

Keep three variables a, b, c for T(i - 3), T(i - 2), T(i - 1). The new term is a + b + c, and then the window slides one step to the right: a takes b, b takes c, c takes the sum. When the loop reaches n, c is the answer.

Approach: Bottom-up with three rolling variables

  1. If n == 0, return 0. If n is 1 or 2, return 1.
  2. Set a = 0, b = 1, c = 1, the three seeds.
  3. For i from 3 to n, compute next = a + b + c, which is T(i).
  4. Slide the window: a = b, b = c, c = next. Now the three variables hold T(i - 2), T(i - 1), T(i).
  5. After the loop, return c.

Step-by-step example

n = 4
  1. n is 4, which is not one of the seeds, so the loop runs.
  2. Start with a = 0, b = 1, c = 1 for T(0), T(1), T(2).
  3. i = 3: next = 0 + 1 + 1 = 2. Slide: a = 1, b = 1, c = 2.
  4. i = 4: next = 1 + 1 + 2 = 4. Slide: a = 1, b = 2, c = 4.
  5. The loop ends at n, so the function returns c = 4.

Code: Python, Java, C++

1class Solution:
2    def tribonacci(self, n: int) -> int:
3        if n == 0:
4            return 0
5        if n < 3:
6            return 1
7        a, b, c = 0, 1, 1
8        for _ in range(3, n + 1):
9            a, b, c = b, c, a + b + c
10        return c
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The loop runs n - 2 times and each pass does two additions and three assignments.

Space

O(1)

Only the three variables a, b, c are stored, whatever the value of n.

Other approaches

Plain recursion (time O(1.84^n), space O(n))

Translate the definition directly. Each call makes three more calls, so the same terms get recomputed an exponential number of times.

Memoized recursion or DP array (time O(n), space O(n))

Store each T(k) the first time it is computed, in a cache or a table filled from 0 upward. Each term is computed once, but all n of them are kept when only three are ever read again.

Matrix exponentiation (time O(log n), space O(1))

Raise the 3x3 transition matrix [[1,1,1],[1,0,0],[0,1,0]] to the power n with repeated squaring. Useful for huge n, but overkill when n is at most 37.

Common mistakes

  • Getting the seeds wrong. T(1) and T(2) are both 1, and T(0) is 0. Returning 1 for n = 0 is a common slip.
  • Updating the variables in the wrong order in languages without tuple assignment. Compute next first, then shift a = b, b = c, c = next.
  • Starting the loop at the wrong index. With seeds for indices 0 to 2 already loaded, the loop starts at 3 and includes n.

Frequently asked questions

Does the answer overflow a 32-bit integer?

No. The problem caps n at 37, and T(37) = 2,082,876,103, which is just under 2^31 - 1. T(38) would overflow, which is why the limit sits where it does.

How is this different from Fibonacci?

The only changes are a third seed and a third term in the sum. The rolling window grows from two variables to three, and the loop starts at index 3 instead of 2.

Why not just use an array?

An array of size n + 1 works and is easy to read, but each step only reads the last three entries. Three variables give the same answer with constant memory.

Is a precomputed table acceptable?

Yes. With only 38 possible inputs you could hard-code all answers. Interviewers usually want the loop, though, since it shows you see the rolling window.