#1137

N-th Tribonacci Number

Easy
MathDynamic ProgrammingMemoizationDynamic ProgrammingMemoizationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to store previously calculated Tribonacci numbers, avoiding redundant calculations and significantly improving efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an array F of length n+1 to store Tribonacci numbers.
  2. 2Step 2: Initialize F[0] = 0, F[1] = 1, F[2] = 1.
  3. 3Step 3: Use a loop from 3 to n, setting F[i] = F[i-1] + F[i-2] + F[i-3].
  4. 4Step 4: Return F[n].
solution.py6 lines
1def tribonacci(n):
2    F = [0] * (n + 1)
3    F[0], F[1], F[2] = 0, 1, 1
4    for i in range(3, n + 1):
5        F[i] = F[i - 1] + F[i - 2] + F[i - 3]
6    return F[n]

Complexity note: The time complexity is O(n) because we compute each Tribonacci number once. The space complexity is O(n) due to the array storing the results of each computation.

  • 1Dynamic programming can significantly reduce time complexity by storing intermediate results.
  • 2Understanding the recursive relationships helps in formulating the optimal solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.