Nth Fibonacci Number

Easy

The Fibonacci numbers are defined as F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2) for n>=2. Given n, return F(n).

Examples

InputOutput
n = 21
n = 43

Python Solution

def fib(n: int) -> int:
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

JavaScript Solution

function fib(n) {
  if (n <= 1) return n;
  let a = 0, b = 1;
  for (let i = 2; i <= n; i++) {
    [a, b] = [b, a + b];
  }
  return b;
}

Step-by-Step Explanation

  1. Iterative approach: only need the last two values.
  2. Start with a=0, b=1. Each step: a becomes b, b becomes a+b.
  3. After n-1 iterations, b holds F(n).

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

MathDynamic Programming

Related Problems

All Problems