Sourav Dey
LeetCode Question - 509. Fibonacci Number πŸ€ͺ

LeetCode Question - 509. Fibonacci Number πŸ€ͺ

6th July 2022 | πŸ—“ Daily LeetCode Challenge - #6

4 min read β€’ 06 Jul, 2022


Read more blogs from the leetcode Series β†’

Share the blog


LeetCode Question - 509. Fibonacci Number πŸ€ͺ

About the Series

Problem-solving is a key skill set for any tech-related stuff you might be working on.

When it comes to developers it's one of the most crucial skills which is needed in almost any day-to-day code you might be writing.

So, this series of blogs is all about practicing Daily LeetCode Challenges & Problem-solving. πŸš€

Problem Statement

Fibonacci Number

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

  • F(0) = 0, F(1) = 1
  • F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

Example 1:

Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Video Explanation

Solution 1: Recursive Approach

Algorithm

Code in JS πŸ§‘β€πŸ’»

/**
 * @param {number} n
 * @return {number}
 */
var fib = function (n) {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
};

Time Complexity : O(n)

Space Complexity: O(n)

Solution 2: Iterative approach with an array

Algorithm

Code in JS πŸ§‘β€πŸ’»

/**
 * @param {number} n
 * @return {number}
 */
var fib = function (n) {
  if (n < 2) return n;
  var fibArray = [];
  fibArray[0] = 0;
  fibArray[1] = 1;
  for (var i = 2; i <= n; i++) {
    fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
  }
  return fibArray[n];
};

Time Complexity : O(n)

Space Complexity: O(n)

Solution 3: Iterative approach without an array

Algorithm

The approach is similar to the 2nd solution but it is done without using a new array.

Code in JS πŸ§‘β€πŸ’»

/**
 * @param {number} n
 * @return {number}
 */
var fib = function (n) {
  if (n < 2) return n;
  var f1 = 0;
  var f2 = 1;
  for (var i = 2; i <= n; i++) {
    var currentSum = f1 + f2;
    f1 = f2;
    f2 = currentSum;
  }
  return f2;
};

Time Complexity : O(n)

Space Complexity: O(1)

Similar Questions for practice

Now it is time to try some similar questions

You can find me on the web 🌍

Add your solution or approach in the comments below. Also, show your love by Sharing the blog. πŸ€—

β€œBelief creates the actual fact.”

~ William James