Last active
July 8, 2023 23:40
-
-
Save optimistiks/ce123a3cf48a68ac0cf80a4d14761986 to your computer and use it in GitHub Desktop.
Given a number n, calculate the corresponding Tribonacci number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function findTribonacci(n) { | |
| // we use an array of fixed size so we keep a constant amount of subproblem solutions at each iteration | |
| // therefore ensuring constant space complexity | |
| const dp = [0, 1, 1]; | |
| if (n < 3) { | |
| return dp[n]; | |
| } | |
| for (let i = 3; i <= n; ++i) { | |
| const result = dp[0] + dp[1] + dp[2]; | |
| dp[0] = dp[1]; | |
| dp[1] = dp[2]; | |
| dp[2] = result; | |
| } | |
| return dp[2]; | |
| } | |
| // tc: O(n) | |
| // sc: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment