DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on • Edited on

1

LeetCode #509 Fibonacci Number with JavaScript

Solutions to LeetCode's 509. Fibonacci Number with JavaScript.

Solution 1: Recursive

/**
 * @param {number} n
 * @return {number}
 */
const fib = (n) => {
  if (n === 0) return 0;
  if (n === 1) return 1;
  return fib(n - 1) + fib(n - 2);
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(2^n)
  • Space complexity: O(n)

This code is simple and easy to read, but it is not suitable for cases where the argument n has a large value because the time complexity is O(2^n).

Solution 2: Iterative

/**
 * @param {number} n
 * @return {number}
 */
const fib = (n) => {
  let fibSequence = [0, 1];
  for (let i = 2; i <= n; i++) {
    fibSequence.push(fibSequence[i - 1] + fibSequence[i - 2]);
  }
  return fibSequence[n];
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)

It is less readable than recursive, but the time complexity is O(n), so if there is a possibility of large values in the argument n, this is better.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay