09 Sept 2026Go / Python / TypeScriptEasy

N-th Tribonacci Number

Compute the sequence where each term is the sum of the previous three terms.

Iterate from the three base values while retaining only the latest three terms.

complexity

O(n) time and O(1) space.

solution files

  • Go n-th-tribonacci-number/solution.go
  • Python n-th-tribonacci-number/solution.py
  • TypeScript n-th-tribonacci-number/solution.ts

Solution files

Gon-th-tribonacci-number/solution.go
package main

func tribonacci(n int) int {
	if n == 0 {
		return 0
	}
	first, second, third := 0, 1, 1
	for index := 3; index <= n; index++ {
		first, second, third = second, third, first+second+third
	}
	return third
}
Pythonn-th-tribonacci-number/solution.py
class Solution:
    def tribonacci(self, n: int) -> int:
        if n == class="syntax-number">0: return class="syntax-number">0
        first, second, third = class="syntax-number">0, class="syntax-number">1, class="syntax-number">1
        for _ in range(class="syntax-number">3, n + class="syntax-number">1): first, second, third = second, third, first + second + third
        return third
TypeScriptn-th-tribonacci-number/solution.ts
function tribonacci(n: number): number {
  if (n === class="syntax-number">0) return class="syntax-number">0; if (n < class="syntax-number">3) return class="syntax-number">1;
  let first = class="syntax-number">0; let second = class="syntax-number">1; let third = class="syntax-number">1;
  for (let index = class="syntax-number">3; index <= n; index += class="syntax-number">1) [first, second, third] = [second, third, first + second + third];
  return third;
}