Coding Challenge Practice - Question 114

Published: (February 4, 2026 at 08:26 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem Description

The task is to find the n-th Fibonacci number. Fibonacci numbers are the sum of the previous two numbers in the sequence, which starts with 0 and 1.

Solution Explanation

  • If n is 0 or 1, the result is n itself.
  • Otherwise, iterate from 2 up to n, keeping track of the two most recent numbers (prev and curr).
  • In each iteration compute next = prev + curr, then shift the variables: prev = curr, curr = next.
  • After the loop, curr holds the n-th Fibonacci number.

Reference Implementation (JavaScript)

function fib(n) {
  // Return n for the base cases 0 and 1
  if (n <= 1) return n;

  let prev = 0;
  let curr = 1;

  // Build the sequence up to n
  for (let i = 2; i <= n; i++) {
    const next = prev + curr;
    prev = curr;
    curr = next;
  }

  return curr;
}
Back to Blog

Related posts

Read more »