
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].
- Start with the first two Fibonacci numbers: 0 and 1.
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].
- Start with the first two Fibonacci numbers: 0 and 1.
Constraints
- 1 ≤ n ≤ 50
- You must return an array containing the first n Fibonacci numbers
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
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. |
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