Sequence NODE_149
MediumGenerate Fibonacci Sequence
JavaScript
Technical Specification
Return an array containing the first n numbers of the Fibonacci sequence.
Input/Output Samples
Input:5
Output:[0, 1, 1, 2, 3]
Optimal Logic Path
function fibonacci(n) {
if (n <= 0) return [];
if (n === 1) return [0];
const arr = [0, 1];
while (arr.length < n) {
const next = arr[arr.length - 1] + arr[arr.length - 2];
arr.push(next);
}
return arr;
}Architectural Deep-Dive
We iteratively build the sequence, always pushing the sum of the last two elements.