Find Nth Fibonacci number (Tabulation)

Given a positive integer n, find the nth Fibonacci number. Fibonacci numbers, when it starts from 0, are calculaed as F(n), where F(1) = 0, F(2) = 1, and F(n) = F(n-1) + F(n-2) for n > 2. Example of first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Hint

Building upon understanding of Fibonacci number (Memoization). Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def fib(n):
  if n < 2:
    return 0

  if n == 2:
    return 1

  result = 0
  prev_1 = 1
  prev_2 = 0
  
  for i in range(3, n + 1):
    result = prev_1 + prev_2
    prev_2 = prev_1
    prev_1 = result

  return result

n = 5

print(fib(n))
// Javascript implementation
function fib(n) {
  if (n < 2) {
    return 0;
  }

  if (n == 2) {
    return 1;
  }

  let result = 0;
  let prev_1 = 1;
  let prev_2 = 0;
  
  for (let i = 3; i <= n; i++) {
    result = prev_1 + prev_2;
    prev_2 = prev_1;
    prev_1 = result;
  }

  return result;
}

const n = 5;

console.log(fib(n));