InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

N-th Tribonacci Number

easy Original β†—
Solving tips
  • This is Fibonacci with a 3-wide look-back: T(k) = T(k-1)+T(k-2)+T(k-3).
  • Slide three rolling variables with simultaneous assignment a,b,c = b,c,a+b+c for O(n) time, O(1) space.
  • Get the base cases right: T(0)=0, T(1)=1, T(2)=1 (note T(2) is 1, not 2), and short-circuit n<3.
  • Avoid plain recursion - three branches per call is ~O(3^n) and re-derives lower terms billions of times.

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 = 4 β†’ 4 β€” the sequence starts 0, 1, 1, 2, 4; T(3) = 0+1+1 = 2, T(4) = 1+1+2 = 4.
  • n = 25 β†’ 1389537.
  • n = 0 β†’ 0 β€” the very first term.

Constraints

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

Like Fibonacci, the tiny bound means any linear method is trivial; the trap is the exponential naive recursion, which re-expands three branches per call.

Think about it first

Hint 1 This is Fibonacci with a window of *three* previous terms instead of two. Write the recurrence directly, then worry about not recomputing.
Hint 2 Plain recursion makes three recursive calls each level β†’ roughly `3^n` work, all of it recomputing the same terms. Cache each `T(k)`, or better, 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.