How to answer a programming interview question

I spent a few hours on Friday doing mock interviews for CS undergrads.  The idea was to help them experience the interview process without the pressure of having a job on the line.  The session was interactive with lots of stopping for advice.  I found myself explaining the following to most of the candidates.  I hope you find some value in it.

  1. Explain the algorithm that you will use to solve the problem.  Use visuals where you can.  This will accomplish two things.  First, it will make sure you understand what you are going to do before you start coding.  This in turn will reduce the number of corrections and backtracks you have to make while coding.  Second, it will give the interviewer a chance to help you correct course early.  This means getting onto the right track before you spend a lot of time coding a solution to the wrong problem.
  2. Write the code.  Use a real programming language.  Tell the interviewer what language you are using and then write in it.  Don’t sweat the syntax.  Focus on the flow of the code.  Using a real language is important because it is too easy to gloss over the important things with pseudo-code.  Try to write the code in one pass.  You already have the algorithm figured out so you shouldn’t need to backtrack and change your code.
  3. Walk through the code with real data.  Before you declare yourself “done”, take the time to walk through the code.  Take a real example and explain how each line of code operates on it.  This will a) give you a chance to find bugs and b)demonstrate to the interviewer that the code works.  Pay careful attention here.  I’ve seen a number of candidates with big bugs in their code explain how they want the code to work instead of how it really works.  If you don’t pay attention, you won’t find the bugs.
  4. If you are interviewing for a test developer position, test your code.  You’ll be asked to do so anyway, you might as well get credit for taking the initiative.  Even if you aren’t interviewing as an SDET, it is a good idea to show that you are thinking through the failure cases.