Tutorialspoint
Problem
Solution
Submissions

Fibonacci Sequence

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to generate the first n numbers of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the sequence starts: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Example 1
  • Input: n = 7
  • Output: [0, 1, 1, 2, 3, 5, 8]
  • Explanation:
    • Start with the first two Fibonacci numbers: 0 and 1.
    • The third number is 0 + 1 = 1.
    • The fourth number is 1 + 1 = 2.
    • The fifth number is 1 + 2 = 3.
    • The sixth number is 2 + 3 = 5.
    • The seventh number is 3 + 5 = 8.
    • Therefore, the first 7 Fibonacci numbers are [0, 1, 1, 2, 3, 5, 8].
Example 2
  • Input: n = 5
  • Output: [0, 1, 1, 2, 3]
  • Explanation:
    • Start with the first two Fibonacci numbers: 0 and 1.
    • The third number is 0 + 1 = 1.
    • The fourth number is 1 + 1 = 2.
    • The fifth number is 1 + 2 = 3.
    • Therefore, the first 5 Fibonacci numbers are [0, 1, 1, 2, 3].
Constraints
  • 1 ≤ n ≤ 50
  • You must return an array containing the first n Fibonacci numbers
  • Time Complexity: O(n)
  • Space Complexity: O(n)
NumberControl StructuresCapgeminiLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Initialize an array to store the Fibonacci sequence
  • Handle the base cases for n = 1 and n = 2
  • Use a loop to calculate each subsequent Fibonacci number
  • Each number is the sum of the two previous numbers in the sequence
  • Add each calculated number to the result array

Steps to solve by this approach:

 Step 1: Check if n is valid and handle edge cases (n <= 0, n = 1).
 Step 2: Initialize an array with the first two Fibonacci numbers [0, 1].
 Step 3: Use a loop starting from index 2 to generate remaining numbers.
 Step 4: Calculate each new Fibonacci number by adding the two previous numbers.
 Step 5: Store each calculated number in the array at the current index.
 Step 6: Continue the loop until we have generated n numbers.
 Step 7: Return the completed Fibonacci sequence array.

Submitted Code :