Fibonacci sequence (recursion)

Easy TimeO(2ⁿ) SpaceO(n)

The Fibonacci sequence starts 0, 1, and every term after that is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13. Given a position n, return the term sitting there. Counting starts at 0, so term 0 is 0 and term 1 is 1, and n is never negative.

Examples

Example 1

Input
n = 5
Output
5
0, 1, 1, 2, 3, 5 — position 5 holds 5, which is a coincidence worth not reading into.

Example 2

Input
n = 7
Output
13
0, 1, 1, 2, 3, 5, 8, 13 — eight terms, and position 7 is the last of them.

The Code

function fib(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
}
fib(5);
Done
Step through fib(5) call by call