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


Author: Michael Jasper

Michael is a Web Developer located in Northern Utah. When not programming, he enjoys spending time with his family, exploring the great-outdoors, and hit-and-miss cooking experiments.

  • I’d have opted for something along the lines of this:

    • Adam

      Agreed with Stu – although that JS solution is not optimal, it may not need to be.
      Mike’s solution is horrible though. Hard to read, lot of unnecessary “edge case” testing. And using recursion for this? Please…

  • Paddy McCarthy

    I’ve created a Rosetta Code task based on the problem you mention. Currently their are solutions in D and Python and hopefully others will be added.