The Fibonacci sequence starts with 0 and 1. Every later term is the sum of the two terms right before it, so the sequence goes 0, 1, 1, 2, 3, 5, 8, 13 and on.
Write F(i) for the term at position i, with F(0) = 0 and F(1) = 1. Given a whole number n, return F(n).
Example 1
Input: n = 6 Output: 8 Why: F(5) + F(4) = 5 + 3 = 8
2 more examples and the constraints
Example 2
Input: n = 0 Output: 0 Why: the sequence starts at 0
Example 3
Input: n = 10 Output: 55 Why: F(9) + F(8) = 34 + 21 = 55
Constraints
- 0 ≤ n ≤ 30
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionO(2ⁿ)
- Bottom-up tableO(n)
- Two 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 = 30 | Verdict |
|---|---|---|---|
| Plain recursion | O(2ⁿ) | Mention it, then fix it | |
| Bottom-up table | O(n) | Passes; keeps a whole table | |
| Two variables | O(n) | Best; constant memory |
n = the position asked for.
Edge cases to test
- n = 0. The answer is 0. Code that assumes at least two terms may read past the array.
- n = 1. The answer is 1, straight from the starting values.
- n = 30. F(30) = 832,040, which fits in a 32-bit integer.
Common mistakes
- Making the table size n, so
dp[1]does not exist when n = 0. - Updating
abefore computing the sum, which loses the old value. - Running the loop one time too many, which returns F(n + 1) instead of F(n).
How to talk through it
- 1Clarify. Is F(0) = 0 or 1 here? How large can n get, and does the answer fit in an int?
- 2Give the recursion. It mirrors the definition; say it is exponential because the same values are solved many times.
- 3Remove the repeats. Store each value once, in a memo or a bottom-up table: O(n).
- 4Shrink the memory. Only the last two values are read, so two variables are enough: O(1) space.
- 5Test out loud. Run n = 0, n = 1 and n = 6 through the loop.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?