Lately, I have been conducting interviews at my workplace. Though it’s fun and I enjoy it, I find it hard to calibrate a candidate’s mental aptitude in a short interview. My co-worker often complains that my interview process is too time consuming as we have been experimenting with two on one interviews(two interviewers, one interviewee).
Another problem is to keep asking the same questions over and over which is kind of boring. Since I wanted to check the candidate’s grasp on recursion, I opted to ask a different question from the top of my head rather than the usual factorial algorithm. So, here is the question I asked:
Assuming the first two members of a Fibonacci series are one and three, write a function using recursion that calculates the n-th member of the series. The argument to the function will be the position number of the member you wish to find.
The candidate answered the question in about three to five minutes but after reading his code and compiling it in my head, I realized this was a question I myself was not prepared to answer yet. So, after staring at his code for about three minutes, I only nodded with a nervous “hhhmmm”.
Since not being able to solve a programming problem is taken as a personal offence by me, I took out some time to code the correct solution in the Ruby language. For those of you who want to try it yourself, move no further as the answer is posted below.
def get_fibonacci_at(place) if place == 1 return 1 elsif place == 2 return 3 else return get_fibonacci_at(place-1) + get_fibonacci_at(place-2) end end
Pretty neat, right? So, now you have a new tool in your arsenal to bug all those people who find recursion hard to understand.
Is there a better implementation than mine? I would love to have a look at it in the comments.