Fibonacci Sequence (Medium)
Good afternoon! Here's our prompt for today.
You may see this problem at Indeed, Apple, Zillow, Splunk, Snowflake, Cockroach Labs, and Digitate.
Implement a function that returns the Fibonnaci number for a given integer input. In a Fibonacci sequence, each number is the sum of the two preceding ones.
The simplest is the series: 1, 1, 2, 3, 5, 8, etc.
This is because:
SNIPPET
1fibonacci(0) = 0
2fibonacci(1) = 1
3fibonacci(2) = 1
4fibonacci(3) = 1 + 1 = 2
5fibonacci(4) = 1 + 2 = 3
6fibonacci(5) = 2 + 3 = 5So if we were to invoke fibonacci(5), we'd want to return 5 (because the second to last number was 2 + last number was 3).
Constraints
- The value of
nwill always be a non negative integer and<=40 - The answer is guaranteed to fit in the integer data type
- Expected time and space complexity are both
O(n)
xxxxxxxxxx36
var assert = require('assert');/* * @param {number} n The Fibonacci number to get. * @returns {number} The nth Fibonacci number */function fibonacci(num) { // fill this in return num;}try { assert.equal(fibonacci(1), 1); console.log('PASSED: ' + '`fibonacci(1)` should return `1`');} catch (err) { console.log(err);}try { assert.equal(fibonacci(17), 1597); console.log('PASSED: ' + '`fibonacci(17)` should return `1597`');} catch (err) { console.log(err);}OUTPUT
Results will appear here.