fill in the gaps exercise - return second biggest element in list (7)

5 Name: #!/usr/bin/anonymous : 2011-04-02 03:52 ID:Heaven

> way more tricky

I disagree. It still lends itself easily to a straightforward constant-space algorithm. The only complexity is that the code no longer can be done with ad-hoc variables, so it pretty much forces you to handle the top-n subset of your input data as a sorted array. (Which, pedagogically speaking, is a very good thing. Variables like "fifth_biggest" give me nervous tics.)

You're basically sorting the input, and pruning the sorted list as you go along. The queue is never going to exceed n items, and after the input is exhausted, you pluck the bottom (nth) item from the queue. You could do a modified insert/merge-sort algorithm with a "falling-off" effect. It involves, instead of manually handling the individual elements, making a separate array to store the top N elements of your incoming data.

This thread has been closed. You cannot post in this thread any longer.