LeetCode 1137: N-th Tribonacci Number Solution

Master LeetCode problem 1137 (N-th Tribonacci Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1137. N-th Tribonacci Number

Problem Explanation

Explanation

  • We can solve this problem using a simple dynamic programming approach.
  • We will create an array to store the Tribonacci numbers up to index n.
  • We initialize the first three values in the array as 0, 1, 1 respectively.
  • Then we iterate from index 3 to n, calculating the Tribonacci number at each index using the formula Tn = Tn-1 + Tn-2 + Tn-3.
  • Finally, we return the value at index n as the result.

Time Complexity: O(n)
Space Complexity: O(n)

Solution Code

class Solution {
    public int tribonacci(int n) {
        if (n == 0) return 0;
        if (n == 1 || n == 2) return 1;
        
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 1;
        
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i-1] + dp[i-2] + dp[i-3];
        }
        
        return dp[n];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1137 (N-th Tribonacci Number)?

This page provides optimized solutions for LeetCode problem 1137 (N-th Tribonacci Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1137 (N-th Tribonacci Number)?

The time complexity for LeetCode 1137 (N-th Tribonacci Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1137 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1137 in Java, C++, or Python.

Back to LeetCode Solutions