N-th Tribonacci Number - Problem

The Tribonacci sequence Tn is defined as follows:

  • T0 = 0
  • T1 = 1
  • T2 = 1
  • Tn+3 = Tn + Tn+1 + Tn+2 for n ≥ 0

Given n, return the value of Tn.

Note: This is a variation of the famous Fibonacci sequence where each term is the sum of the three preceding ones instead of two.

Input & Output

Example 1 — Small Value
$ Input: n = 4
Output: 4
💡 Note: T(4) = T(1) + T(2) + T(3) = 1 + 1 + 2 = 4. The sequence is: T(0)=0, T(1)=1, T(2)=1, T(3)=2, T(4)=4.
Example 2 — Base Case
$ Input: n = 0
Output: 0
💡 Note: T(0) = 0 by definition. This is one of the base cases.
Example 3 — Another Base Case
$ Input: n = 2
Output: 1
💡 Note: T(2) = 1 by definition. Both T(1) and T(2) equal 1 as base cases.

Constraints

  • 0 ≤ n ≤ 37
  • The answer is guaranteed to fit in a 32-bit integer

Visualization

Tap to expand
N-th Tribonacci Number INPUT Definition: T0 = 0 T1 = 1 T2 = 1 Tn+3 = Tn + Tn+1 + Tn+2 Sequence Visualization: T0 T1 T2 T3 T4 0 1 1 2 ? Input: n = 4 ALGORITHM STEPS 1 Initialize 3 variables a=0, b=1, c=1 2 Loop from i=3 to n for i in range(3, n+1) 3 Calculate next value next = a + b + c 4 Shift variables a=b, b=c, c=next Iteration Table: i a b c next init 0 1 1 - 3 1 1 2 2 4 1 2 4 4 FINAL RESULT Complete Tribonacci Sequence: T0 0 T1 1 T2 1 T3 2 T4 4 T4 = T1 + T2 + T3 4 = 1 + 1 + 2 Output: 4 OK - Verified! Space: O(1) Time: O(n) Key Insight: Space-Optimized DP uses only 3 variables instead of an array. Since each Tribonacci number depends only on the previous 3 values, we can slide a window of 3 variables through the sequence, reducing space complexity from O(n) to O(1) while maintaining O(n) time complexity. TutorialsPoint - N-th Tribonacci Number | Space-Optimized DP Approach
Asked in
Facebook 15 Google 12 Amazon 8
180.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen