N-th Tribonacci Number — LeetCode 1137 Python Solution

EasyMemoizationMathDynamic Programming
Problem
#1137
Reading time
2 min

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

Python
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 a

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview