N-th Tribonacci Number
Problem
Given an integer n, return the n-th Tribonacci number where T0 = 0, T1 = 1, T2 = 1, and Tn = Tn-1 + Tn-2 + Tn-3 for n >= 3.
- 0 ≤ n ≤ 37
Example
n = 44The Tribonacci sequence starts as 0, 1, 1, 2, 4, ... For n=4, the value is T3 + T2 + T1 = 2 + 1 + 1 = 4. The algorithm handles base cases directly and iteratively computes subsequent values by summing the previous three.
Approach
Straightforward Solution
A naive recursive solution directly implements the recurrence but results in exponential time due to repeated calculations of the same subproblems.
Core Observation
The Tribonacci number at position n depends solely on the sum of the three preceding numbers, forming a linear recurrence relation with fixed base cases.
Path to Optimal
Recognizing the overlapping subproblems and optimal substructure, the problem is suited for dynamic programming. Instead of recursion, an iterative approach with constant space tracks only the last three computed values, enabling efficient computation.
Optimal Approach
Use three variables to store the last three Tribonacci numbers and iteratively update them from 3 up to n. This approach achieves O(n) time and O(1) auxiliary space, directly computing the n-th Tribonacci number without recursion or extra memory.
Time
O(n)
The algorithm iterates from 3 to n once, performing constant-time operations per iteration, resulting in linear time complexity.
Space
O(1)
Only three variables are used to store intermediate Tribonacci values, so the auxiliary space is constant regardless of input size.
Pattern Spotlight
Dynamic Programming (Iterative State Compression)
When a linear recurrence depends only on a fixed number of previous states, maintain just those states in variables and iteratively update them to achieve O(1) space and O(n) time.
Solution
| 1 | class Solution: |
| 2 | def tribonacci(self, n: int) -> int: |
| 3 | if n == 0: |
| 4 | return 0 |
| 5 | |
| 6 | if n <= 2: |
| 7 | return 1 |
| 8 | |
| 9 | a = 0 |
| 10 | b = 1 |
| 11 | c = 1 |
| 12 | |
| 13 | for _ in range(3, n + 1): |
| 14 | next_value = a + b + c |
| 15 | a = b |
| 16 | b = c |
| 17 | c = next_value |
| 18 | |
| 19 | return c |
Step-by-Step Solution
Return Base Cases Directly for n = 0, 1, or 2
| 3 | if n == 0: |
| 4 | return 0 |
| 6 | if n <= 2: |
| 7 | return 1 |
Objective
To handle the trivial cases where the Tribonacci number is known without iteration.
Key Insight
The first three Tribonacci numbers are fixed and defined explicitly. Returning these values immediately avoids unnecessary computation and simplifies the iterative logic by ensuring n >= 3 for the loop.
Interview Quick-Check
Core Logic
Directly returning known base cases prevents redundant computation and sets clear boundaries for the iterative process.
State & Boundaries
The conditions `n == 0` and `n <= 2` partition the input domain into base cases and the iterative case.
Common Pitfalls & Bugs
Failing to handle base cases separately can cause index errors or incorrect results in the iterative loop.
Iteratively Compute Tribonacci Numbers Using Rolling Variables
| 9 | a = 0 |
| 10 | b = 1 |
| 11 | c = 1 |
| 13 | for _ in range(3, n + 1): |
| 14 | next_value = a + b + c |
| 15 | a = b |
| 16 | b = c |
| 17 | c = next_value |
Objective
To compute the n-th Tribonacci number by iteratively summing the previous three values and updating state variables.
Key Insight
By maintaining only the last three Tribonacci numbers in variables, the algorithm compresses state and avoids storing the entire sequence. Each iteration calculates the next number as the sum of these three, then shifts the variables forward. This approach leverages the linear recurrence's fixed dependency window to achieve efficient computation.
Interview Quick-Check
Core Logic
The iterative update `next_value = a + b + c` followed by shifting `a, b, c` captures the recurrence relation and state progression in constant space.
State & Boundaries
The loop runs from 3 to n inclusive, ensuring all necessary Tribonacci numbers are computed sequentially.
Common Pitfalls & Bugs
Incorrectly updating variables out of order can corrupt the state and produce wrong results.
Complexity
This loop runs in O(n) time and uses O(1) auxiliary space, optimal for this problem.
Return the Computed n-th Tribonacci Number
| 19 | return c |
Objective
To output the final computed Tribonacci number after completing the iteration.
Key Insight
After the loop completes, the variable `c` holds the n-th Tribonacci number due to the rolling update logic. Returning this value provides the correct result for all n >= 3.
Interview Quick-Check
Core Logic
Returning `c` leverages the invariant that `c` always holds the latest Tribonacci number after each iteration.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
next_value = a + b + c
Calculate the next Tribonacci number as the sum of the previous three.
This line implements the core recurrence relation, which defines the Tribonacci sequence.
return c
Return the computed n-th Tribonacci number stored in c.
After completing the iteration, `c` holds the correct Tribonacci number for n, making it the correct return value.
if n == 0:
Check if n equals 0 to handle the first base case.
This condition immediately returns the known Tribonacci value for n=0, avoiding unnecessary computation and simplifying subsequent logic.
return 0
Return 0 for the base case n=0.
Returning 0 here directly encodes the definition of the Tribonacci sequence's initial value.
if n <= 2:
Check if n is less than or equal to 2 to handle other base cases.
This condition captures the remaining base cases where the Tribonacci number is 1, enabling early return and preventing iteration for small n.
return 1
Return 1 for base cases n=1 or n=2.
This line encodes the Tribonacci sequence's definition for these positions, ensuring correctness for small inputs.
a = b
Shift variable a to hold the previous b value.
Updating `a` to `b` advances the rolling window, discarding the oldest value and preparing for the next iteration.
b = c
Shift variable b to hold the previous c value.
Updating `b` to `c` continues the rolling window shift, maintaining the correct sequence of values.
c = next_value
Assign the newly computed next_value to c.
Updating `c` to the new Tribonacci number completes the rolling window update, ensuring `c` always holds the latest value.
for _ in range(3, n + 1):
Iterate from 3 up to n inclusive to compute Tribonacci numbers.
This loop systematically computes each Tribonacci number in sequence, ensuring all intermediate values are correctly calculated.
a = 0
Initialize variable a to store T0 = 0.
Variable `a` holds the oldest Tribonacci number in the rolling window, forming the foundation for iterative computation.
b = 1
Initialize variable b to store T1 = 1.
Variable `b` holds the middle Tribonacci number in the rolling window, essential for the recurrence calculation.
c = 1
Initialize variable c to store T2 = 1.
Variable `c` holds the most recent Tribonacci number in the rolling window, which will be updated iteratively.
Test Your Understanding
Why is it sufficient to store only the last three Tribonacci numbers when computing the n-th number?
Because the Tribonacci recurrence depends exclusively on the three immediately preceding numbers, storing only these three values at each step provides all necessary information to compute the next number without retaining the entire sequence.
Related Problems
Dynamic Programming pattern
Don't just read it. Drill it.
Reconstruct N-th Tribonacci Number from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the N-th Tribonacci Number drill