470.Fibonacci Series — From Recursion to Space-Optimized DP
Easy
The Fibonacci series starts 0, 1 and every further term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Given a position n, return the n-th term of this series.
This one problem is the cleanest way to see the entire DP progression in miniature. Plain recursion follows the definition exactly but recomputes the same smaller values over and over, so its cost explodes exponentially. Memoization fixes that by caching each answer the first time it's worked out, turning the same recursion tree into linear work. Tabulation builds the same values from the bottom up in a loop instead, with no recursion at all. And since each step only ever needs the two values right before it, the whole dp array can finally be collapsed into two rolling variables — constant space, same linear time.
Example 1:
Input: n = 5
Output: 5
Example 2:
Input: n = 10
Output: 55
Example 3:
Input: n = 0
Output: 0
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 25 - ●
fib(0) = 0, fib(1) = 1, and fib(n) = fib(n-1) + fib(n-2) for n ≥ 2
n =
5