N-th Tribonacci Number — LeetCode 1137 Python Solution
- Problem
- #1137
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn.
Example
- Input
- n = 4
- Output
- 4
- Explanation
- T_3 = 0 + 1 + 1 = 2
Python solution
class Solution:
def tribonacci(self, n: int) -> int:
a, b, c = 0, 1, 1
for _ in range(n):
a, b, c = b, c, a + b + c
return aComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1137. N-th Tribonacci Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 1137. N-th Tribonacci Number?
- LeetCode 1137. N-th Tribonacci Number is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1137. N-th Tribonacci Number?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1137. N-th Tribonacci Number?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1137. N-th Tribonacci Number cover?
- LeetCode 1137. N-th Tribonacci Number is tagged Memoization, Math and Dynamic Programming on LeetCode.