InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

N-th Tribonacci Number

easy Original ↗ 00:00

Problem

The Tribonacci sequence is defined by:

  • T(0) = 0, T(1) = 1, T(2) = 1
  • T(k) = T(k-1) + T(k-2) + T(k-3) for k >= 3

Given an integer n, return T(n).

Examples

  • n = 44 — the sequence starts 0, 1, 1, 2, 4; T(3) = 0+1+1 = 2, T(4) = 1+1+2 = 4.
  • n = 251389537.
  • n = 00 — the very first term.

Constraints

  • 0 <= n <= 37
  • The answer fits in a signed 32-bit integer.

Like Fibonacci, the small bound means any linear method is fast enough. The pitfall is naive recursion, which re-expands three branches per call and runs in exponential time.

Think about it first

Hint 1 This is Fibonacci with a window of three previous terms instead of two. Write the recurrence directly, then avoid recomputing terms.
Hint 2 Plain recursion makes three recursive calls per level, roughly `3^n` work, all of it recomputing the same terms. Cache each `T(k)`, or build up from `T(0)` in a loop.
Hint 3 Bottom-up you only ever need the last three values. Keep three variables `a, b, c` and slide them forward: `a, b, c = b, c, a+b+c`. O(n) time, O(1) space. Handle `n < 3` as base cases.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug