Facebook Pixel

1137. N-th Tribonacci Number

Problem Description

The Tribonacci sequence is a sequence of numbers where each number is the sum of the three preceding numbers. The sequence is defined as follows:

  • T₀ = 0
  • T₁ = 1
  • T₂ = 1
  • For n ≥ 0: Tₙ₊₃ = Tₙ + Tₙ₊₁ + Tₙ₊₂

Given an integer n, you need to calculate and return the value of Tₙ (the nth Tribonacci number).

For example:

  • T₃ = T₀ + T₁ + T₂ = 0 + 1 + 1 = 2
  • T₄ = T₁ + T₂ + T₃ = 1 + 1 + 2 = 4
  • T₅ = T₂ + T₃ + T₄ = 1 + 2 + 4 = 7

The problem asks you to implement a function that takes n as input and returns the corresponding Tribonacci number at position n in the sequence.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key observation is that to calculate any Tribonacci number, we only need the three immediately preceding numbers. This is similar to the Fibonacci sequence, but instead of summing two numbers, we sum three.

Starting from the base cases T₀ = 0, T₁ = 1, and T₂ = 1, we can build up to Tₙ by repeatedly calculating the next number in the sequence. However, we don't need to store all the numbers we calculate along the way - we only need to keep track of the most recent three values at any given time.

Think of it like climbing stairs where you can see only the last three steps behind you. As you move forward to calculate the next number, you can "forget" the oldest value and shift your window of three numbers forward. This sliding window approach means we can solve the problem using constant space O(1) instead of storing an entire array of size n.

The solution uses three variables a, b, and c to represent this sliding window. Initially, they hold T₀, T₁, and T₂. Then, for each iteration:

  • The new value becomes a + b + c (sum of the current three)
  • We shift the window: a becomes the old b, b becomes the old c, and c becomes the new sum
  • After n iterations, a will hold Tₙ

This approach elegantly handles all cases including when n = 0, 1, or 2, as the loop will execute the appropriate number of times to position the answer in variable a.

Learn more about Memoization, Math and Dynamic Programming patterns.

Solution Approach

The solution uses dynamic programming with space optimization to calculate the nth Tribonacci number. Instead of maintaining an array to store all values from T₀ to Tₙ, we use three variables to track only the most recent three values needed for the calculation.

Implementation Details:

  1. Initialize three variables:

    • a = 0 (represents T₀)
    • b = 1 (represents T₁)
    • c = 1 (represents T₂)
  2. Iterate n times: The loop runs exactly n times. In each iteration, we perform a simultaneous update:

    a, b, c = b, c, a + b + c

    This single line does three things at once:

    • The new a gets the value of the old b
    • The new b gets the value of the old c
    • The new c gets the sum of the old a + b + c
  3. Return the result: After n iterations, variable a contains Tₙ.

How the sliding window works:

  • Before iteration 1: a=T₀, b=T₁, c=T₂
  • After iteration 1: a=T₁, b=T₂, c=T₃
  • After iteration 2: a=T₂, b=T₃, c=T₄
  • ...
  • After iteration n: a=Tₙ, b=Tₙ₊₁, c=Tₙ₊₂

The beauty of this approach is that it naturally handles edge cases:

  • When n=0: The loop doesn't execute, returning a=0 which is T₀
  • When n=1: The loop executes once, returning a=1 which is T₁
  • When n=2: The loop executes twice, returning a=1 which is T₂

Time Complexity: O(n) - we perform exactly n iterations Space Complexity: O(1) - we only use three variables regardless of the input size

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's calculate T₅ (the 5th Tribonacci number) step by step using our solution approach.

Initial Setup:

  • We start with a = 0 (T₀), b = 1 (T₁), c = 1 (T₂)
  • We need to iterate 5 times to reach T₅

Iteration 1:

  • Current values: a = 0, b = 1, c = 1
  • Calculate new value: a + b + c = 0 + 1 + 1 = 2
  • Update (shift window): a = 1, b = 1, c = 2
  • Now we have: a = T₁, b = T₂, c = T₃

Iteration 2:

  • Current values: a = 1, b = 1, c = 2
  • Calculate new value: a + b + c = 1 + 1 + 2 = 4
  • Update (shift window): a = 1, b = 2, c = 4
  • Now we have: a = T₂, b = T₃, c = T₄

Iteration 3:

  • Current values: a = 1, b = 2, c = 4
  • Calculate new value: a + b + c = 1 + 2 + 4 = 7
  • Update (shift window): a = 2, b = 4, c = 7
  • Now we have: a = T₃, b = T₄, c = T₅

Iteration 4:

  • Current values: a = 2, b = 4, c = 7
  • Calculate new value: a + b + c = 2 + 4 + 7 = 13
  • Update (shift window): a = 4, b = 7, c = 13
  • Now we have: a = T₄, b = T₅, c = T₆

Iteration 5:

  • Current values: a = 4, b = 7, c = 13
  • Calculate new value: a + b + c = 4 + 7 + 13 = 24
  • Update (shift window): a = 7, b = 13, c = 24
  • Now we have: a = T₅, b = T₆, c = T₇

Result: After 5 iterations, a = 7, which is T₅.

We can verify: T₅ = T₂ + T₃ + T₄ = 1 + 2 + 4 = 7 ✓

Notice how our sliding window of three variables (a, b, c) moves through the sequence, always maintaining the three most recent values we need for the next calculation.

Solution Implementation

1class Solution:
2    def tribonacci(self, n: int) -> int:
3        """
4        Calculate the n-th Tribonacci number.
5      
6        The Tribonacci sequence is defined as:
7        T(0) = 0, T(1) = 1, T(2) = 1
8        T(n) = T(n-1) + T(n-2) + T(n-3) for n >= 3
9      
10        Args:
11            n: The index of the Tribonacci number to calculate (0-indexed)
12          
13        Returns:
14            The n-th Tribonacci number
15        """
16        # Initialize the first three Tribonacci numbers
17        # T(0) = 0, T(1) = 1, T(2) = 1
18        t0, t1, t2 = 0, 1, 1
19      
20        # Iterate n times to calculate the n-th Tribonacci number
21        # Each iteration shifts the window forward by one position
22        for _ in range(n):
23            # Simultaneous assignment to shift the sliding window
24            # t0 becomes t1 (move forward)
25            # t1 becomes t2 (move forward)
26            # t2 becomes the sum of previous three values (new Tribonacci number)
27            t0, t1, t2 = t1, t2, t0 + t1 + t2
28      
29        # After n iterations, t0 holds the n-th Tribonacci number
30        return t0
31
1class Solution {
2    /**
3     * Calculates the nth Tribonacci number.
4     * The Tribonacci sequence is defined as:
5     * T(0) = 0, T(1) = 1, T(2) = 1
6     * T(n) = T(n-1) + T(n-2) + T(n-3) for n >= 3
7     * 
8     * @param n The index of the Tribonacci number to calculate (0-indexed)
9     * @return The nth Tribonacci number
10     */
11    public int tribonacci(int n) {
12        // Initialize the first three Tribonacci numbers
13        int first = 0;   // T(0) = 0
14        int second = 1;  // T(1) = 1
15        int third = 1;   // T(2) = 1
16      
17        // Iterate n times to shift the window forward
18        while (n-- > 0) {
19            // Calculate the next number in the sequence
20            int next = first + second + third;
21          
22            // Shift the window: move each value one position to the left
23            first = second;
24            second = third;
25            third = next;
26        }
27      
28        // After n iterations, 'first' contains the nth Tribonacci number
29        return first;
30    }
31}
32
1class Solution {
2public:
3    int tribonacci(int n) {
4        // Initialize the first three Tribonacci numbers
5        // T0 = 0, T1 = 1, T2 = 1
6        long long first = 0;
7        long long second = 1;
8        long long third = 1;
9      
10        // Iterate n times to calculate the nth Tribonacci number
11        while (n--) {
12            // Calculate the next Tribonacci number as sum of previous three
13            long long next = first + second + third;
14          
15            // Shift the window: move each value one position forward
16            first = second;
17            second = third;
18            third = next;
19        }
20      
21        // After n iterations, 'first' contains the nth Tribonacci number
22        return static_cast<int>(first);
23    }
24};
25
1/**
2 * Calculates the nth Tribonacci number
3 * The Tribonacci sequence is defined as:
4 * T(0) = 0, T(1) = 1, T(2) = 1
5 * T(n) = T(n-1) + T(n-2) + T(n-3) for n >= 3
6 * 
7 * @param n - The index of the Tribonacci number to calculate (0-indexed)
8 * @returns The nth Tribonacci number
9 */
10function tribonacci(n: number): number {
11    // Initialize the first three Tribonacci numbers
12    let first: number = 0;   // T(0) = 0
13    let second: number = 1;  // T(1) = 1
14    let third: number = 1;   // T(2) = 1
15  
16    // Iterate n times to calculate the nth Tribonacci number
17    while (n > 0) {
18        // Calculate the next number in the sequence
19        const next: number = first + second + third;
20      
21        // Shift the window: move each value one position to the left
22        first = second;
23        second = third;
24        third = next;
25      
26        // Decrement the counter
27        n--;
28    }
29  
30    // After n iterations, 'first' contains the nth Tribonacci number
31    return first;
32}
33

Time and Space Complexity

Time Complexity: O(n)

The algorithm uses a single for loop that iterates exactly n times. In each iteration, it performs a constant amount of work (three variable assignments with basic arithmetic operations). Therefore, the total time complexity is linear with respect to the input n.

Space Complexity: O(1)

The algorithm only uses three variables (a, b, and c) to store the intermediate values regardless of the size of n. No additional data structures are created that grow with the input size. The space usage remains constant throughout the execution, resulting in constant space complexity.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Incorrect Variable Update Order

One of the most common mistakes is trying to update the variables sequentially instead of simultaneously:

Incorrect Implementation:

def tribonacci(self, n: int) -> int:
    a, b, c = 0, 1, 1
    for _ in range(n):
        a = b  # a is now updated
        b = c  # b is now updated
        c = a + b + c  # WRONG! Uses the NEW values of a and b
    return a

Problem: When updating c = a + b + c, we're using the already-updated values of a and b instead of their original values. This completely breaks the algorithm.

Solution: Use simultaneous assignment with tuple unpacking:

a, b, c = b, c, a + b + c  # All values on the right are evaluated BEFORE any assignment

2. Off-by-One Error in Loop Count

Another pitfall is confusion about how many iterations are needed:

Incorrect Implementation:

def tribonacci(self, n: int) -> int:
    a, b, c = 0, 1, 1
    for _ in range(n + 1):  # WRONG! One too many iterations
        a, b, c = b, c, a + b + c
    return a

Problem: Running the loop n+1 times will return T(n+1) instead of T(n).

Solution: The loop should run exactly n times. Think of it this way:

  • Start with a = T(0)
  • After 0 iterations: a = T(0)
  • After 1 iteration: a = T(1)
  • After n iterations: a = T(n)

3. Misunderstanding the Return Value

Some might think they need to return different variables based on the value of n:

Incorrect Implementation:

def tribonacci(self, n: int) -> int:
    if n == 0: return 0
    if n == 1: return 1
    if n == 2: return 1
  
    a, b, c = 0, 1, 1
    for _ in range(n - 2):  # Adjusting loop count
        a, b, c = b, c, a + b + c
    return c  # Returning c instead of a

Problem: This adds unnecessary complexity and is prone to errors in calculating the correct loop count and return value.

Solution: Trust the elegant sliding window approach - always return a after exactly n iterations. The algorithm naturally handles all edge cases without special conditions.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which type of traversal does breadth first search do?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More