LeetCode Problem no. 1137

FAIZAL. S. A
Towards Dev
Published in
2 min readApr 24, 2024

--

Question no. 1137. N-th Tribonacci Number

class Solution {
public int tribonacci(int n) {
if(n == 0)
return 0;

ArrayList<Integer> list = new ArrayList<>();

list.add(0);
list.add(1);
list.add(1);

for(int i=2; i<n; i++){
list.add(list.get(list.size()-1)+list.get(list.size()-2)+list.get(list.size()-3));
}

return list.get(list.size()-1);

}
}
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0

arr = [0, 1, 1]

for i in range(2, n):
arr.append(arr[-1] + arr[-2] + arr[-3])

return arr[-1]

Normal explanation of the code:

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.

In my approach, I have utilized an array to store the numbers of the Tribonacci sequence up to the number provided in the question, and then I return the last value stored in the list or array.

Technical explanation of the code:

I have used the simple mathematical logic.

  1. public int tribonacci(int n): This is the method declaration. It’s a public method that takes an integer n as input and returns an integer.
  2. if(n == 0) return 0;: If the input n is 0, the method immediately returns 0. This is because the 0th number in the Tribonacci sequence is 0.
  3. ArrayList<Integer> list = new ArrayList<>();: This line initializes an ArrayList of integers. This list will be used to store the Tribonacci numbers.
  4. list.add(0); list.add(1); list.add(1);: These lines add the first three numbers of the Tribonacci sequence (0, 1, 1) to the list.
  5. for(int i=2; i<n; i++): This is a for loop that starts from 2 and runs until n. The reason it starts from 2 is because the first three numbers of the Tribonacci sequence are already added to the list.
  6. list.add(list.get(list.size()-1)+list.get(list.size()-2)+list.get(list.size()-3));: Inside the for loop, this line calculates the next number in the Tribonacci sequence by adding the last three numbers in the list and adds it to the list.
  7. return list.get(list.size()-1);: After the for loop, this line returns the last number in the list, which is the nth number in the Tribonacci sequence.

This problem can be solve this by using the recursive method also.

Results for Python and java

--

--