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.
- Recursion with memoO(n)
- Bottom-up, three variablesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 37 | Verdict |
|---|---|---|---|
| Recursion with memo | O(n) | Passes; O(n) memory | |
| Bottom-up, three variables | O(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
cgives 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,bandcone 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
- 1Clarify. What are the first three values? How large can n get, and does the answer fit in an int?
- 2Write the recurrence. T(k) = T(k − 1) + T(k − 2) + T(k − 3), with seeds 0, 1, 1.
- 3Say why plain recursion is slow. The same values are computed many times; a memo fixes that in one line.
- 4Shrink the memory. Only the last three values are ever read, so keep three variables and loop up to n.
- 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?