So I have been doing interview questions and programming puzzles lately and it occurred to me that a lot of them are not very relevant to the actual daily lives of a programmer. Here’s an example. A somewhat frequently asked programming question is “given an array of N unsorted elements, what’s the best way to find the X highest element”? The simple answer is to use a common sort like quicksort and then find the X highest element. That isn’t the fastest way, because you’ll spend a lot of time sorting the whole array when you really only want part of it sorted. The correct answer is to use a heap sort and then just find the X highest element. This generally should save a lot of time. However the reality of being in software is that I have never once in my 7+ years as a developer actually implemented either a quicksort or a heap sort in my life. And I haven’t even had an occasion to make a decision of that type.
Giving credit for knowledge of algorithms and correctness in this situation is nice, but from a software engineering perspective, the simpler solution is for most cases better because it is simpler and has far fewer lines of code and therefore will be less error prone. If I were a manager and I wanted someone to get the Xth element of array, I’d much rather have them use an already implemented sort to sort the whole thing and then traverse it to take the Xth element. In java, it’d amount to just a few lines of code. Of course if the sort time is huge then it is worthwhile to implement the correct solution.
