Thoughts, stories and ideas.

Dissecting an interview question

So, it’s time to retire my interview question. It feels like people are doing better on it than they used to (Glassdoor?), and frankly, I’ve asked it so many times that just walking into an interview room is enough to make me want to start chewing my own arm off. Still, if I’m going to stop asking it, then I thought it might be useful to dissect how and why it worked, common mistakes, and so on. I did this a little obliquely in a previous post, but this will be the real deal.

The problem

First, let’s go over the problem itself (I use Java in the code samples below, though I allow candidates to write the code in C, C++, C#, Java, or Python). I have a little script that I’ve developed over the years, that lets me describe the problem as succinctly and concretely as possible:

I’d like for you to implement a binary search tree (BST) class. There are two requirements. The first requirement is that when I initially instantiate a binary search tree object, I would like for it to start out empty. That is to say, with no initial values. Secondly, I would like to be able to insert specifically ints into the binary search tree. So, I don’t want this to be generic/templated – it should be a data structure specifically for use with ints. Does that make sense?

A couple more things. First of all, I don’t want you to worry about balancing the BST (wait for sigh of relief from interviewee). Also, don’t bother writing getters and setters – they’re just boilerplate code, and I don’t want us to waste time on that. You can either assume that an appropriate getter or setter exists, or access elements directly – either way, it doesn’t matter to me. Lastly, don’t worry about any other feature of the binary search tree. For example, don’t worry about removing values from the binary search tree.

To summarize, all that I want is for you to write a binary search tree class that starts out empty, and that you can insert ints into. Does that make sense?

At this point, I write the following on the whiteboard in whatever language they had chosen:

BST t = new BST();
t.insert(10);
t.insert(20);
t.insert(5);
t.insert(15);
t.insert(30);

    10
   /  \
  5    20
      /  \
    15    30

For the coding portion of the interview, I’m not trying to test whether they know what a BST is or not – I want to make sure they have a visual representation of what we’re doing, so that even candidates whose CS101 might be a little weak can complete the problem.

But first, a note to the haters

Before proceeding to the discussion, I’d like to acknowledge and address a couple of complaints. Though they don’t come up that often, they’re common enough that I’d like to just get them out of the way up front.

  • “I haven’t done this since college.”

The only reason I do a binary search tree problem is that most people know what they are, and the problem is easy to describe quickly. Even if you haven’t studied or used BSTs in a while – even if I have to explain them to you on the spot – you should be able to complete the problem without much difficulty. It’s one step more complicated than a linked list problem, and Lord knows those have been done to death.

  • “Normally, I would just use a library, or google it.”

Sure – me too. Except that the goal of this exercise is not to prove that you know how to use libraries or the internet, but that you can solve a very simple coding exercise. Most people can’t program. Hell, most programmers can’t program. This is my version of fizzbuzz, and if you can’t do it, then you aren’t going to be able to solve completely novel problems.

  • “The traditional whiteboard coding exercise is a bad way to interview people.”

I’m open to other approaches, but all of the alternatives I’ve seen are unrealistic for the majority of top candidates (most of whom are currently employed, are interviewing with other companies, and have a limited amount of time to make a decision). And while I’m sympathetic to this opinion, it’s also completely irrelevant. Unless you’re going to limit the companies you apply to based on their interview style, you don’t get to choose how you get interviewed.

Back to our regularly scheduled program, already in progress

One of the reasons I like the BST problem is that there are a lot of different valid solutions. I don’t like problems where you have to make an intuitive leap, or figure out a trick in order to get to a solution – I much prefer evaluating candidates on core coding skills, and deductive problem solving ability. The other nice thing about the problem is that it tests candidates in a variety of ways. It’s an OOP design problem wrapped in a logical puzzle, inside a coding challenge. Following are some common solutions:

One class v1
public class BST {
    private BST left, right;
    private Integer value;
}
One class v2
public class BST {
    private BST left, right;
    private int value;
    private boolean isInitialized;
}
Two classes v1
public class Node {
    private Node left, right;
    private int value;
}

public class BST {
    private Node root;
}
Two classes v2 (inner class)
public class BST {
    private Node root;

    private static class Node {
        Node left, right;
        int value;
    }
}
Iterative insert
public void insert(int value){
    if (root == null) {
        root = new Node(value);
        return;
    }
    Node cur = root;
    while (true) {
        if (value < cur.value) {
            if (cur.left == null) {
                cur.left = new Node(value);
                break;
            }
            cur = cur.left;
        }
        else {
            if (cur.right == null) {
                cur.right = new Node(value);
                break;
            }
            cur = cur.right;
        }
    }
}
Recursive insert v1
public void insert(int value) {
    if (root == null) {
        root = new Node(value);
        return;
    }
    insertHelper(root,value);
}

private static void insertHelper(Node n, int value) {
    if (value < n.value) {
        if (n.left == null)
            n.left = new Node(value);
        else
            insertHelper(n.left,value);
    }
    else {
        if (n.right == null)
            n.right = new Node(value);
        else
            insertHelper(n.right,value);
    }
}
Recursive insert v2 (kind of functional)
public void insert(int value) {
    root = insertHelper(root,value);
}

private static Node insertHelper(Node n, int value) {
    if (n == null)
        n = new Node(value);
    else if (value < n.value)
        n.left = insertHelper(n.left,value);
    else
        n.right = insertHelper(n.right,value);
    return n;
}

All of the above are valid answers – I don’t ding candidates for any of them, though to be honest I find the one class versions a little ugly. They don’t allow meta-data to be stored with the top-level tree, and require additional information to be stored unnecessarily at each node. Still, as long as the candidate is able to write the code quickly and correctly, I’m willing to accept different approaches.

One of my goals, though, is to make sure the candidate can code both iteratively and recursively. So, if they do the recursive version of insert(), I also ask them to do it iteratively. Look at the code – the first recursive version isn’t really that different from the iterative version (it’s tail-recursive, after all), so it should be easy for them to make the conversion. This feels like a gimme, but some candidates go totally blank. Likewise, if they start with the iterative version of insert(), then I give them another problem that’s easiest to do recursively.

Common mistakes

The following are some of the mistakes that pop up over and over again.

  • Forgetting to handle the base case (i.e., the empty tree).
  • Forgetting to handle the case in which the value already exists. I don’t actually care how people handle this – they can put it to the left or right, add a “count” member to nodes, make the tree a set – but if you first check for a lesser value, then a greater value, then you can end up with an infinite loop in the iterative version.
  • Switching the left and right sides. This generally happens when candidates write the conditional starting with the node value, instead of the parameter (i.e., “if (node.value < value)” instead of “if (value < node.value)”).

The above are mistakes I actually look forward to – they aren’t deal killers, and they give me the opportunity to see if candidates can find bugs in their own code through inspection. The following bug, though, is extraordinarily aggravating. It’s also exceedingly common. Candidates will write this code and then stare at it, unable to figure out why it doesn’t work.

Bad code – iterative version
public void insert(int value) {
    Node cur = root;
    while (cur != null) {
        if (value < cur.value)
            cur = cur.left;
        else
            cur = cur.right;
    }
    cur = new Node(value);
}
Bad code – recursive version
public void insert(int value) {
    insertHelper(root,value);
}

private static void insertHelper(Node n, int value) {
    if (n == null)
        n = new Node(value);
    else if (value < n.value)
        insertHelper(n.left,value);
    else
        insertHelper(n.right,value);
}

Can you see the problem? Once the code gets around to instantiating a new object, it’s being assigned to a local variable or parameter that has no connection to the original data structure. I could understand it if this were an outlier, a weird error that very junior candidates sometimes made, but even senior engineers make this mistake all the time. If you can’t see the bug, look harder, walk through the code, do whatever you need to do to grok what’s happening at a deep level – you absolutely need to understand why the above won’t work.

Brownie points

The problem really is simple enough that there aren’t that many ways to show off, but every once in a while someone does something cool. Usually, this involves using a language-specific feature particularly well. Like in the above examples, using the static keyword correctly (very, very few people do). Or in C++, using double pointers well:

void BST::insert(int value)
{
    Node **cur = &this->root;
    while (*cur) {
        if (value < (*cur)->value)
            cur = &(*cur)->left;
        else
            cur = &(*cur)->right;
    }
    *cur = new Node(value);
}

The above isn’t possible in Java, but if you’re coding in C++, it’s a pretty elegant solution. If you’re going to do this, though, I want you to put all of your ampersands, asterisks, and parentheses in the right place – sure, the compiler or IDE will catch bad assignments, but I want you to show me that you know what you’re doing. If you do, great! You’ve just demonstrated that you understand how pointers work at a deep level. If you don’t, well, I’m going to assume you’re making the same mistake as the people up above.

Scoring

In the interview, I don’t really care about specification of public/private. I don’t care about mistakes an IDE will catch. I don’t care about use of getters/setters vs. direct access of member variables. I’ll give you the obvious Node constructor – no need to waste time writing the boilerplate.

The most important thing is correctness. After that, I care about how clean the code is. There are some things I find annoying, like the following “four ifs” solution:

void insert(int value) {
    if (root == null) {
        root = new Node(value);
        return;
    }
    Node cur = root;
    while (true) {
        if (value < cur.value && cur.left == null) {
            cur.left = new Node(value);
            break;
        }
        else if (value >= cur.value && cur.right == null) {
            cur.right = new Node(value);
            break;
        }
        else if (value < cur.value)
            cur = cur.left;
        else
            cur = cur.right;
    }
}

This code hurts my eyes. Besides which, it’s error prone. It’s too easy to use “>” instead of “>=” in the second if, which can lead to an infinite loop, or to data corruption if the final else doesn’t have a condition. Even if it’s written correctly, it’s an ugly anti-pattern that should be avoided.

The other thing I care about is speed. It’s almost always a bad sign if candidates write really slowly – it’s usually because they don’t feel comfortable coding, are out of practice or aren’t that adept in their supposed “language of choice”. Candidates who have trouble with basic syntax, or who think in individual keywords instead of phrases, aren’t going to be successful in a fast-paced environment.

Last thoughts

So there you have it. It was never a question designed to expose brilliance, but I felt that it served me well in evaluating a candidate’s basic ability to code. As with any tool, I came to understand it better over time, learned which parts to pay attention to and which to throw away. Sometimes, the hardest part of an interview is just not getting stuck on the wrong thing. I have a new question now, something quite different – it’ll be interesting to see where this one goes.

If you liked this post, you’ll also like:

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.