EasyNo. 1137

N-th Tribonacci Number — LeetCode 1137 Python Solution

Topics
Memoization, Math, Dynamic Programming
On a study list
LeetCode 75
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0070Climbing StairsEasy
0241Different Ways to Add ParenthesesMedium
0464Can I WinMedium
0509Fibonacci NumberEasy
0913Cat and MouseHard
0964Least Operators to Express NumberHard

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.

Free to download. Check it runs on your machine, then pick a plan.