This is an interview favorite with companies like Oracle, Apple and Microsoft even today. It's often used as a replacement for the famed "Fizz-Buzz" test, and interviewers like to use it as a quick sanity test to check if you're comfortable with the basics of programming. Let's code!

Approach 1

Hint: Recursion

F(n) = F(n-1) + F(n-2), base conditions: F(0) = 0, F(1) = 1

Implementation:

// Base Condition
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);

This has got an exponential time complexity. T(n) = T(n-1) + T(n-2), which makes it inefficient for larger inputs. Also, if you see the implementation, F(n-2) will be calculated for F(n) and also for F(n-1), which is a repetitive work.
That’s why the interviewer WILL ask for a better solution.

Approach 2

Hint: Dynamic Programming

Store the Fibonacci numbers calculated so far and use them to calculate the next input in a single pass.

Implementation

This does have an additional space complexity of O(n). The time complexity, however, becomes O(n).

Neat, isn't it? Let's see if we can do something about that space complexity.

Approach 3

Hint: Store the last two numbers.

In the above solution we have used an array to store the output at every step, which increases the space complexity of the problem. Let us avoid that by storing only the previous two fibonacci numbers. After all, you only need the last two numbers to calculate the next number!