Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Last active July 8, 2023 23:40
Show Gist options
  • Select an option

  • Save optimistiks/ce123a3cf48a68ac0cf80a4d14761986 to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/ce123a3cf48a68ac0cf80a4d14761986 to your computer and use it in GitHub Desktop.
Given a number n, calculate the corresponding Tribonacci number.
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