This is a puzzle, so you’re not allowed to look at the suggested solution until you have your own solution.

Your task is to write a function that makes that determination. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

My O(n log n) solution is similar to the one given. I did keep one quick check in that’s not
strictly necessary, though: if k times the first (smallest) element is bigger than t, then we
needn’t bother adding things up. This is a remnant from when I first started working on the
problem. I was trying to find things that would reduce the amount of work needed in
O(n log n) time or less before I came upon the final answer. Since it’s a quick check for small
first values, I’ve kept it in.

I got asked a variant of this question in a phone interview for Google. I basically used the sorting solution above, but my interviewer told me there’s a better solution. Instead, if you use a data structure like a BST or a heap, size-bounded at k elements, and replacing the largest element when you find something smaller than it, you can reduce the complexity from O(n log n) to O(n log k). In the worst case scenario, where k = n, the complexity will become O(n log n), but otherwise it will be quicker. Thanks for the coding puzzles, and keep up the good work!

the ‘better’ solution will not even get the first line coded by the time {t > +/ k take sort V} gets coded. One could use the remaining time to find an idiomatic shortcut to k take sort V, which is what Matt described with the data structure solution, like:

t > +/ k take_sort V

Note, that kind of optimization not being obvious with an algoloid language.