Tuesday, May 31, 2011

Dealing with unexpected complexity

I sometimes use this as an interview question for senior programmers, and the real part of the interview question isn't about the code at all.  It's about how people deal with unexpected complexity.  I start the problem off with this seemingly absurdly simple programming test: Please write code to accept two integers, and return the numbers in an array in sorted order.

Sometimes I see code like this:

int[] SortTwo(int i, int j) {
  int[] result = new int[] {i, j};
  result.sort();
  return result;
}

My comment about this is to ask them to remove the sort() call and code everything themselves, after which I'll get something like this:

int[] SortTwo(int i, int j) {
  if (i < j)
    return new int[] {i, j};

  else
    return new int[] {j, i};
}

And here's where things get interesting.  I say I'm going to change the problem now to SortThree(), and still insist they not use any external function calls.  So I change the signature to look like this: 



int[] SortThree(int i, int j, int k);

and them ask them to write the code to return three numbers sorted in an array.  The interesting thing here is that the code to sort three numbers is "unexpectedly" more complex than the code to sort two numbers.  The real point of this question is to see how a person deals with unexpected complexity.  Here's a solution in Java.