File: n-th-tribonacci-number/solution.py

Date: 2026-06-06

Time: 18:12

Purpose

This file implements LeetCode 1137 — N-th Tribonacci Number. It owns exactly one responsibility: computing the n-th value of the Tribonacci sequence, defined as:

Key Components

Solution.tribonacci(self, n: int) -> int — The sole method. Takes an index n (0 through 37 per the problem constraints) and returns the corresponding Tribonacci number.

Patterns

Iterative sliding window over recurrence state. Rather than memoization or recursion, the solution keeps exactly three variables (a, b, c) representing the last three values in the sequence and advances them via simultaneous tuple assignment:


a, b, c = b, c, a + b + c

This is the same idiom used in the classic iterative Fibonacci — extended from two state variables to three. The tuple swap is idiomatic Python: all right-hand-side values are evaluated before any assignment, so no temporary variable is needed.

Early return for base cases. The two if guards at lines 13–16 handle n == 0 and n <= 2 before entering the loop. This keeps the loop's range (3..n) clean — it never runs for n < 3.

Dependencies

Imports: None. The solution is self-contained with no standard library or third-party dependencies.

Imported by: The n-th-tribonacci-number/test_solution.py file directly tests this class. The massive "Imported By" list in the prompt is an artifact of the repo's test harness structure — those other test files don't actually import *this* solution; they share a common test runner or import pattern.

Flow

1. If n == 0, return 0 immediately.

2. If n is 1 or 2, return 1 immediately.

3. Initialize (a, b, c) = (0, 1, 1), representing T(0), T(1), T(2).

4. Loop from 3 to n inclusive. Each iteration shifts the window forward: a becomes the old b, b becomes the old c, and c becomes the sum of all three old values.

5. After the loop, c holds T(n). Return it.

Invariants

Error Handling

None. The method trusts that n satisfies 0 <= n <= 37 per the LeetCode contract. Negative n would fall through both guards and enter a range(3, n+1) that produces no iterations, returning c = 1 — silently wrong but not an exception. This is typical for LeetCode solutions where input constraints are guaranteed by the judge.

Topics to Explore

Beliefs