Tribonacci Sequence

Moderate
0/80
profile
Contributed by
1 upvote
Asked in company
OLX Group

Problem statement

You are given an integer ‘N’. Your task is to find out the ‘N’th Tribonacci Number. ‘N’th number in the Tribonacci sequence is defined as Tn = T n - 1 + Tn - 2 + Tn - 3. Where T0 = 0, T1 = 1, T2= 1. Return the answer in mod of 109 + 7.

For Example :
You are given ‘N’ = 5, Here we know 0th, 1st and 2nd Tribonacci numbers are 0, 1 and 1 respectively. Therefore we can calculate the 3rd number as 0 + 1 + 1 = 2 and 4th number as 1 + 1 + 2 = 4 and 5th number as 1 + 2 + 4 = 7. Hence the answer is 7.
Follow Up :
Can you solve it in logarithmic time?
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first input line contains a single integer ‘T’ representing the number of test cases.

The first line of each test case contains a single integer ‘N’ representing Tribonacci number to find.
Output Format :
For each test case, print a single integer, representing the ‘N’th Tribonacci Number.

Print a separate line for each test case.
Constraints :
1 ≤ T ≤10
0 ≤ N ≤ 10^5

Time Limit: 1 sec
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function. 
Sample Input 1 :
2
5
2
Sample Output 1 :
7
1
Explanation for Sample Input 1:
For the first test case, ‘N’ = 5, Here we know 0th, 1st and 2nd Tribonacci numbers are 0, 1 and 1 respectively. Therefore we can calculate the 3rd number as 0 + 1 + 1 = 2 and 4th number as 1 + 1 + 2 = 4 and 5th number as 1 + 2 + 4 = 7. Hence the answer is 7.

For the second test case, ‘N’ = 2, Here, the second number in the Tribonacci sequence is already defined as 1. Hence the answer is 1.
Sample Input 2 :
2
0
9
Sample Output 2 :
0
81
Hint

Try to solve it in a brute force manner.

Approaches (4)
Brute Force

In this approach, we will make the function recursive, since and then add the base cases the Tribonacci sequence that is given in the question.

We will implement it as `F(n) = F(n - 1) + F(n - 2) + F(n - 3)`

 

Algorithm:

  • If ‘N’ is 0 return 0
  • If ‘N’ is 1 or 2 return 1
  • Otherwise recursively call the function on ‘N’ - 1, ‘N’ - 2 and ‘N’ - 3 and return the sum of all function calls with a mod of 10^9 + 7
Time Complexity

O( 3 ^ N ), where N is the given integer

 

For each function call, we are making 3 subsequent function calls. Hence the total number of recursive calls is ~3 ^ N

Hence the overall time complexity is O( 3 ^ N ).

Space Complexity

O( N ), where N is the given integer

 

The space complexity of the recursion stack is ~N.

Hence the final space complexity is O( N )

Code Solution
(100% EXP penalty)
Tribonacci Sequence
Full screen
Console