hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

N-th Tribonacci Number


  • Approach:

    1. Like the Fibonacci series problem, we have three initial numbers are given.

    2. The next number is the sum previous three numbers.

    3. So declare three integers, zero, one, and two that hold three numbers for figuring out another integer three.

    4. For N < 3 return the given value.

    5. And for N >= 3, start running a loop from 3 to N.

    6. Calculate three = zero + one + two.

    7. For each iteration, till N, assign zero = one, one = two, and two = three.

    8. Return three at the end.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(1)


Code [C++]

class Solution {

public:

int tribonacci(int n) {

if(n == 0) return 0;

if(n == 1) return 1;

if(n == 2) return 1;

int zero = 0, one = 1, two = 1, three;

for(int i=3; i<=n; i++){

three = zero + one + two;

zero = one, one = two, two = three;

}

return three;

}

};