Ultimate guide to write clean code during whiteboard interviews

These two coding blocks do the same thing. Yet, they read very differently.

Block 1:

StringBuilder b = new StringBuilder();
int end = input.length() - 1;

for (int i = input.length() - 1; i >= 0; i--) {
    if (input.charAt(i) == ' ' && i + 1 < input.length() && i <= end) {
        String w = input.substring(i+1, end+1);
        b.append(w);
        b.append(" ");
        end = i-1;
    }
}

String w = input.substring(0, end+1);
b.append(w);

System.out.println(b);

Block 2:

public static String reverseWords(String sentence) {
    StringBuilder resultBuilder = new StringBuilder();
    int currentWordEnd = sentence.length() - 1;

    for (int i = sentence.length() - 1; i >= 0; i--) {
        if (sentence.charAt(i) == ' ') {
            int currentWordStart = i + 1;

            // returns '' for invalid input
            String currentWord = getSubstring(sentence, currentWordStart, currentWordEnd);

            if (!currentWord.isEmpty())
                resultBuilder.append(currentWord + " ");
            
            currentWordEnd = i - 1; // reset current word
        }
    }
    
    // add first word
    String firstWord = getSubstring(sentence, 0, currentWordEnd);
    if (!firstWord.isEmpty())
        resultBuilder.append(firstWord);

    return resultBuilder.toString();
}

In a whiteboard interview, it should be no surprise that a candidate who codes Block 2 will do better. You don’t want the interviewer leaving like this:

Confused

You want them leaving with clarity:

Excited

Many candidates are way too focused on finding a correct algorithm. Yes, a good algorithm solves the problem, but clean code nails the interview.

Let’s see how to do this.

  1. First comes Structure. This is the foundation of a clean solution.

    Before you start writing, have a clear idea of what you’re going to write.

    Makes sense right? You won’t sound like the Beatles if you don’t know what you’re about to play!

    Ok great, but how do we do that?

    Let’s say you’re making a beautiful drawing. You draw a rough sketch. With that as the guide, you make a well crafted masterpiece.

    Similarly, my favorite step in an interview is to write 4-5 lines of code structure before the actual code. How do you do that?

    Here’s an example of Breadth First Search (BFS):

    initiate a queue
    while queue ! empty
        pop queue and look at node
        add node's neighbors to queue
    

    That’s it! No fancy syntax, no code. Just a few lines to get you primed.

    Now, here’s a catch. Don’t spend more than a minute on this. This should be quick. It’s just a prototype to guide you as you code. Don’t give the interviewer an impression that you are writing code. Tell them that you are writing a few steps of the algorithm before you implement it. They’ll be ok with it.

    Now that you have structure, you’re halfway done with clean code. Yes, half the way. It’s the foundation. Now, you can focus on details.

  2. Write clear function definitions

    Here’s a common mistake: you start coding by declaring variables:

     StringBuilder b = new StringBuilder();
     int end = input.length() - 1;
     ..
     ..
    

    Instead, the first lines of code should be a function definition. This will wrap your solution.

     public static String reverseWords(String sentence) {
    
     }
    

    Here’s why this is important.

    1. It clarifies what the output will be, including:
      • What will be the return type for the output?
      • Does the interveiwer want you to print the answer instead of returning a value?
    2. It clarifies what your input parameters are.

    3. Your interviewer knows exactly what you’re going to deliver in the interview. It’s all packaged up in this function definition.

    A note on picking function names: Make it descriptive.

    It should describe what the function does. Here are a few examples of Java functions. Keep in mind that this might vary by language - other languages might have different conventions, so know your language’s conventions.

     public static int getLargest(int[] a) {
            
     }
    
     public static String reverseWords(String sentence) {
    
     }
    
     public static List<String> getValidWords(String text) {
            
     }
    
     // Interviewer said they want you to print the output
     public static void printPermutations(int[] digits) {
            
     }
    
  3. Use good Variable Names

    The last thing we want -> variables named stu, co and res.

    (Short for student, count and result)

    Just write the full word! Its just 4-5 characters more. It’s not going to take much time.

    And make them descriptive. Something that actually tells you what the variable does.

    Interviewers don’t want to read ‘num’ for a variable that’s actually a counter. Name it counter/count.

    Ask yourself:

    1. What does this variable represent?
      • Does it represent the maximum value? Good names: maxValue, max. Bad names: m, val, mVal
      • Does it represent the result? Good name: result. Bad names: out, r, res
      • Does it represent a list of valid words? Good name: validWords, validWordsList. Bad names: words, valid
    2. Or, what does it do?
      • Does it keep track of the count? Good name: counter/count. Bad names: c, num
      • Does it wrap the values of a Car object? Good name: carWrapper. Bad names: wrapper, car
      • Does it build the result? Good names: resultBuilder, builder. Bad names: result, res, build

    Both these questions may overlap, but it’s helpful to ask those when you’re stuck without a name.

    (Note: the above variable names follow Java conventions. Different languages have different conventions.)

    With practice, naming will come to you automatically.

  4. Use Helper Functions: Place parts of code in helper functions. Specially if you’re going to re-use them.

    • Reused code: For example, if you’re swapping two elements in an array in many parts of the code, just write a swap() helper function. Most of the time, interviewers won’t even ask you to implement it. Time saved, code saved.

    • Isolated logical blocks: Does your code have two broad steps? For example, do you do a Breadth First Search and then go over the results and do some other operation? Put those in different functions. Makes it very clear what the two steps are.

  5. Use Comments

    In your day job, comments communicate code to future readers. Here, though, the scenario is different. The interviewer is already following you. You don’t need detailed comments. So you can utilize smaller comments at key locations. Here are a few examples from the first solution:

     // returns '' for invalid input
     String currentWord = getSubstring(sentence, currentWordStart, currentWordEnd);
    
     currentWordEnd = i; // reset current word
    

    With those two comments, you’ve added an extra level of clarity without wasting much time writing.

    Why smaller comments? Because you don’t want to spend time writing full sentences on a whiteboard!

  6. Review your code while coding

    Great candidates do this subconsciously without even knowing it. Let’s say you write 10 lines of code. You’ve been focused on those 10 lines, so you often lose track of where you are. Well, just go back and review your code. Here’s an example:

    “Ok, so we’ve initialized the queue, and we started removing and analyzing each node. Now all that’s left is visiting each node’s neighbors and adding them back and we should be done.”

    This gives a refresher to both you AND the interviewer. Remember, the interviewer has been sitting the whole time, often bored while you’re thinking through the code. This gives him/her a chance to get back on track.

  7. (BONUS) Bring a fine tip marker to write cleanly.

    Office markers are all used up and broken. Fresh markers give you more space to write so you don’t have to go back and forth erasing code.

Practice these tips while coding solutions at home. You’ll find your code getting better over time. Eventually, it will become second nature to you.

All the best for your interviews!