InterviewSolution
Saved Bookmarks
| 1. |
Get the nth Fibonacci number in O(n) time and O(1) space complexity. |
|
Answer» //Javascriptfunction fib(n){ let [x, y] = [0, 1] while (n > 0){ [x, y] = [y, x + y] n -= 1 } return x} This SOLUTION has a linear time complexity of O(n) and a constant space complexity of O(1). The number of loops required to determine the nth fib number will STILL increase linearly as n increases, but as we extend the sequence out, we are OVERRIDING the previous NUMBERS in the sequence, KEEPING the space complexity constant for any input n. It is often referred to as the Iterative Top-Down Approach. |
|