Interesting interview question #1

During an interview (for a software developer position) with a major employer in the state of Utah, I was asked an interesting programming question:

Create a function that, given an integer parameter, will return the middle three digits

I mentally wiped the sweat away from my forehead: whew — not computing bigO notation, ¬†inventing a new search algorithm, or performing my favorite song!

I verbally walked through my thought process:

There will be a need for some looping to trim off the first and last digit of the integer each iteration — perhaps a while loop with the condition that the value is greater than 99? No, there is a better way: I’ll trim the digits¬†recursively.

I asked for some feedback on my thought process, then set out writing some code. I came up with something like this:

“Nice solution,” the interviewer replied. “How will your function handle 4501?” Uh-oh: It will trim 4 and 1, and return 50. “Hmm… What about 40251?” Darn: It will trim 4 and 5, recursing on 025, which will be interpreted as 25 and fail.

So, as it turns out, programming questions in interviews might not be about creating the elegant, recursive solution — but about asking the right questions. Thorough requirements gathering. ¬†Lesson learned.

After the interview, I couldn’t get the question out of my mind, and spent some time giving it a proper solution: handling input less than 999, error-ing on even values (finding the middle three of an even digit value is a somewhat undefined behavior), and polishing it off with some unit testing.

See a live version here