N-th Tribonacci Number - Problem

The Tribonacci sequence is a fascinating extension of the famous Fibonacci sequence! While Fibonacci numbers are formed by adding the previous two numbers, Tribonacci numbers are formed by adding the previous three numbers.

The sequence is defined as:

  • T0 = 0
  • T1 = 1
  • T2 = 1
  • Tn = Tn-3 + Tn-2 + Tn-1 for n โ‰ฅ 3

For example: 0, 1, 1, 2, 4, 7, 13, 24, 44, 81...

Goal: Given an integer n, return the n-th Tribonacci number Tn.

Input & Output

example_1.py โ€” Python
$ Input: n = 4
โ€บ Output: 4
๐Ÿ’ก Note: T(4) = T(3) + T(2) + T(1) = 2 + 1 + 1 = 4
example_2.py โ€” Python
$ Input: n = 25
โ€บ Output: 1389537
๐Ÿ’ก Note: The 25th Tribonacci number, calculated efficiently using the sliding window approach
example_3.py โ€” Python
$ Input: n = 0
โ€บ Output: 0
๐Ÿ’ก Note: Base case: T(0) = 0 by definition

Constraints

  • 0 โ‰ค n โ‰ค 37
  • Answer is guaranteed to fit within a 32-bit integer
  • The sequence grows exponentially, similar to Fibonacci

Visualization

Tap to expand
Building the Tribonacci TowerT(0)0T(1)1T(2)1T(3)20+1+1T(4)41+1+2T(5)71+2+4Sum of 3 belowSliding WindowKeep only last 3:124Next = 1+2+4 = 7Time: O(n)Space: O(1)โœ“ Optimal!
Understanding the Visualization
1
Foundation
Start with floors 0, 1, 2 having heights 0, 1, 1
2
Build Up
Each new floor = sum of previous 3 floors
3
Slide Window
Keep only the last 3 floor heights in memory
4
Reach Target
Continue until we reach the desired floor n
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window approach with three variables gives us optimal O(n) time and O(1) space complexity, making it the perfect balance of simplicity and efficiency!
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
87.5K Views
Medium Frequency
~12 min Avg. Time
1.8K 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