Tribonacci Number solution explained

To compute the nth Tribonacci number, keep the last three values and slide them forward n times: the new value is the sum of the three, and the window drops its oldest entry. That runs in O(n) time with O(1) space; naive recursion is exponential, and a 3×3 matrix power brings it to O(log n) multiplications if n is huge.

By Published 8 min read

What you are asked to compute

The Tribonacci sequence is the three-term cousin of Fibonacci. It starts 0, 1, 1, and each term after that adds up the previous three. Given a non-negative integer n, return T(n). The problem is small on purpose: it checks whether you can turn a recursive definition into an efficient loop without being told how.

The first terms, computed for this page
n012345678910
T(n)01124713244481149
The first terms, computed for this page. Scroll sideways on a small screen.

Check a couple by hand before coding: T(5) = T(4) + T(3) + T(2) = 4 + 2 + 1 = 7, and T(8) = 24 + 13 + 7 = 44. Ask how large n can be. If n stays in the thirties, the answer fits in a signed 32-bit integer (T(37) is 2,082,876,103, and T(38) is the first term past 2^31 − 1). If n can be much larger, the conversation turns to big integers or modular arithmetic.

Slow approach: translate the definition directly

The definition is already a recursive function. Writing it out takes four lines, and it is a fine first sentence in an interview. The trouble is the call tree: T(n) calls T(n − 1), T(n − 2) and T(n − 3), and each of those fans out again. The number of calls grows like the sequence itself, about 1.84^n, so n = 35 already means more than a billion calls.

def trib_slow(n):
    if n == 0:
        return 0
    if n <= 2:
        return 1
    return trib_slow(n - 1) + trib_slow(n - 2) + trib_slow(n - 3)
Naive recursion: exponential time.

Adding a cache fixes the time. Each T(k) is computed once and then looked up, so the work is O(n), with O(n) memory for the cache and the call stack.

from functools import lru_cache

@lru_cache(maxsize=None)
def trib_memo(n):
    if n < 3:
        return (0, 1, 1)[n]
    return trib_memo(n - 1) + trib_memo(n - 2) + trib_memo(n - 3)
Top-down with a cache: O(n) time, O(n) space.

Main approach: a sliding window of three

Bottom-up is simpler still. Hold three numbers a, b and c that stand for T(i), T(i + 1) and T(i + 2). One step of the loop moves the window up by one: the new triple is b, c and a + b + c. Start the window at i = 0, with (0, 1, 1), and after n steps a holds T(n). Because the loop runs exactly n times, n = 0, 1 and 2 need no special branches.

def tribonacci(n):
    a, b, c = 0, 1, 1  # T(i), T(i + 1), T(i + 2), starting at i = 0
    for _ in range(n):
        a, b, c = b, c, a + b + c
    return a
Python: three rolling values, O(n) time and O(1) space.
function tribonacci(n) {
  let a = 0;
  let b = 1;
  let c = 1;
  for (let i = 0; i < n; i++) {
    [a, b, c] = [b, c, a + b + c];
  }
  return a;
}
JavaScript: the same loop with destructuring assignment.

Python's tuple assignment and JavaScript's destructuring both evaluate the whole right side before assigning, so the old a is still available when computing the sum. In a language without that feature, compute the next value into a temporary first.

When n is large in JavaScript

JavaScript numbers are doubles, which represent integers exactly only up to 2^53. The Tribonacci terms pass that bound at n = 63, and when we ran the plain loop it first returned a wrong value at n = 65. Switching to BigInt keeps every digit.

function tribonacciBig(n) {
  let a = 0n;
  let b = 1n;
  let c = 1n;
  for (let i = 0; i < n; i++) {
    [a, b, c] = [b, c, a + b + c];
  }
  return a;
}
JavaScript: exact results for any n with BigInt.

Follow-up: O(log n) with a matrix power

Write the window as a column vector v(i) = [T(i + 2), T(i + 1), T(i)]. One step of the recurrence is a fixed linear map: the top entry becomes the sum of all three, and the others shift down. As a matrix that is M = [[1, 1, 1], [1, 0, 0], [0, 1, 0]], so v(n) = M^n · v(0) with v(0) = [1, 1, 0]. Raising M to the nth power by repeated squaring needs O(log n) matrix products, each a constant 27 multiplications. In practice this matters when n is in the millions or beyond, and usually comes with a request to return the answer modulo a large prime.

def trib_matrix(n):
    def mul(x, y):
        return [[sum(x[i][k] * y[k][j] for k in range(3)) for j in range(3)]
                for i in range(3)]

    result = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    step = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]
    while n:
        if n & 1:
            result = mul(result, step)
        step = mul(step, step)
        n >>= 1
    # Bottom row of M^n applied to [T(2), T(1), T(0)] = [1, 1, 0] gives T(n).
    return result[2][0] + result[2][1]
Python: fast exponentiation of the 3×3 step matrix.

Complexity

Costs for computing T(n)
MethodTimeExtra space
Naive recursionO(1.84^n), roughlyO(n) stack
Recursion with a cacheO(n)O(n)
Three rolling variablesO(n)O(1)
Matrix exponentiationO(log n) matrix productsO(1)
Costs for computing T(n). Scroll sideways on a small screen.

One caveat worth saying: with exact big integers, each addition costs time proportional to the number of digits, which grows linearly with n. So the "O(n)" loop is really doing more work per step as n grows. Interviewers rarely push this far, but mentioning it shows you know where the model breaks down.

Edge cases

  • n = 0 returns 0, and n = 1 and n = 2 both return 1. The loop version handles all three without branches, which is a good reason to prefer it.
  • Negative n is undefined by the usual statement. Ask, then either reject it or document the behavior.
  • Overflow: in Java or C++, T(38) no longer fits in a signed 32-bit int and needs a 64-bit type; a signed 64-bit type in turn overflows at n = 74.
  • JavaScript precision once terms pass 2^53 (n = 63 and up), covered by the BigInt version above.

Common mistakes

  • Seeding the sequence as 1, 1, 1 or 0, 1, 2. The first three terms are 0, 1, 1; check T(3) = 2 against your table before moving on.
  • Running the loop n − 2 times and returning c, then getting the small cases wrong. Either handle them separately and test them, or use the window that starts at i = 0.
  • Sequential assignment in a language without tuple swaps: a = b; b = c; c = a + b + c uses the updated a and b.
  • Presenting memoized recursion as O(1) space. The cache and the stack are both O(n).
  • Skipping the complexity of the naive version. Saying "exponential, roughly 1.84 to the n" is a quick win.

Talking through it

Fictional example

From definition to loop in three sentences
Candidate
The definition recurses three ways, so a direct recursive version is exponential because the same terms come up again and again.
Candidate
Each term only needs the previous three, so I'll keep a window of three values starting at 0, 1, 1 and shift it n times. After n shifts the first slot is T(n).
Candidate
That's O(n) time and constant space. If n could be enormous, I'd switch to a 3 by 3 matrix power for O(log n) steps, and work modulo whatever the problem asks.

More from this set

The rolling-window idea is the same one that finishes Min Cost Climbing Stairs, where two values are enough. For a sequence whose recurrence sums over every split point rather than a fixed window, continue with Unique Binary Search Trees, which produces the Catalan numbers. The algorithm interview questions page lists the wider set of topics.

Using Natively while you prepare

Warm-up problems like this one are good for practicing how you talk, not only what you type. Natively can transcribe a mock round on your computer so you can see whether you named the exponential version and its cost before optimizing, and it can read a screenshot of a problem and propose an approach to compare with yours afterward. See an AI interview assistant for how that works.

Questions people ask

How do you compute the nth Tribonacci number efficiently?

Keep three variables for T(i), T(i + 1) and T(i + 2), starting at 0, 1, 1, and shift them n times, replacing the window with the last two values plus their sum with the first. That is O(n) time and O(1) space.

What is the time complexity of the recursive Tribonacci solution?

Without caching it is exponential, roughly 1.84^n calls, because the same terms are recomputed many times. With memoization it drops to O(n) time and O(n) space.

Can Tribonacci be computed faster than O(n)?

Yes. Express one step as a 3×3 matrix and raise it to the nth power by repeated squaring, which takes O(log n) matrix products. It is mainly useful for very large n, often with a modulus.

What are the first Tribonacci numbers?

0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149. Each term after the third is the sum of the previous three.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP