## Question

Given an integer n, write a function to compute the nth Fibonacci number.

eg.

`fibonacci(1) = 1`

`fibonacci(5) = 5`

`fibonacci(10) = 55`

Once you think that you’ve solved the problem, click below to see the solution.

*As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.*

## Solution

How was that problem? You can check out the solution in the video below.

Here is the source code for the solution shown in the video:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public long fibonacci(int x) { if (x < 0) return -1; if (x == 0) return 0; long[] cache = new long[x + 1]; for (int i = 1; i < cache.length; i++) { cache[i] = -1; } cache[1] = 1; return fibonacci(x, cache); } private long fibonacci(int x, long[] cache) { if (cache[x] > -1) return cache[x]; cache[x] = fibonacci(x - 1, cache) + fibonacci(x - 2, cache); return cache[x]; } |

Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.