AlgoFrames

Tribonacci with O(1) space

Challenge · Write code · about 15 min

The tribonacci numbers are T(0) = 0, T(1) = 1, T(2) = 1 and T(i) = T(i - 1) + T(i - 2) + T(i - 3). Return T(n).

Use O(1) extra space: keep only the last three values, not a table of n + 1 cells.

Example 1

Input:

[4]

Output:

4

Example 2

Input:

[25]

Output:

1389537

Constraints

  • 0 ≤ n ≤ 37
  • The answer fits in a 32-bit signed integer

Learn the idea first: Tabulation: filling the table bottom-up, a visual lesson.

More Tabulation: filling the table bottom-up problems