Skip to content
Problem 1137 · LeetCode 1137(opens in a new tab)

N-th Tribonacci Number

EasyDynamic programming

The Tribonacci numbers start with 0, 1, 1. After that, every number is the sum of the three numbers right before it: 0, 1, 1, 2, 4, 7, 13, and so on. Call the number at position k T(k), so T(0) = 0, T(1) = 1 and T(2) = 1.

Given n, return T(n).

Example 1

Input:  n = 6
Output: 13
Why:    the sequence runs 0, 1, 1, 2, 4, 7, 13, and 2 + 4 + 7 = 13
2 more examples and the constraints

Example 2

Input:  n = 0
Output: 0
Why:    T(0) is the first seed

Example 3

Input:  n = 10
Output: 149
Why:    T(7) to T(9) are 24, 44 and 81, which add up to 149

Constraints

  • 0 ≤ n ≤ 37
  • T(37) is 2,082,876,103, so the answer fits in a 32-bit signed integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion with memoO(n)
  2. Bottom-up, three variablesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 37Verdict
Recursion with memoO(n)
Passes; O(n) memory
Bottom-up, three variablesO(n)
Best; constant memory

n = the position asked for. Plain recursion without a memo would need billions of calls at n = 37.

Edge cases to test

  • n = 0. Returns 0. A loop-based answer that always returns c gives 1 here.
  • n = 1 or n = 2. Both return 1, straight from the seeds; the loop does not run.
  • Largest n. n = 37 gives 2,082,876,103, just under the 32-bit limit of 2,147,483,647.
  • n = 3. The first computed value: 0 + 1 + 1 = 2.

Common mistakes

  • Returning 1 for n = 0 because the seeds were set up for n ≥ 1.
  • Updating a, b and c one at a time without a temporary, so the sum reads a value already overwritten.
  • Submitting the plain recursion, whose calls grow exponentially.

How to talk through it

  1. 1Clarify. What are the first three values? How large can n get, and does the answer fit in an int?
  2. 2Write the recurrence. T(k) = T(k − 1) + T(k − 2) + T(k − 3), with seeds 0, 1, 1.
  3. 3Say why plain recursion is slow. The same values are computed many times; a memo fixes that in one line.
  4. 4Shrink the memory. Only the last three values are ever read, so keep three variables and loop up to n.
  5. 5Test out loud. Run n = 0, n = 2 and n = 6 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?