How do you find the kth largest element in an array, and what are the options?
There are three main options and they differ in what they spend. Sorting the array and indexing into it costs O of n log n time and no extra space. Keeping a heap of the k largest elements seen so far costs O of n log k time and O of k space. Quickselect partitions the array like quicksort but recurses into only one side, giving O of n average time with O of 1 space.
def kth_largest(values, k):
ordered = sorted(values, reverse=True)
return ordered[k - 1]
data = [3, 2, 1, 5, 6, 4]
print(kth_largest(data, 2))
print(kth_largest(data, 6))The outputs are 5 and 1. The second largest of that array is 5, and the smallest, which is the sixth largest, is 1.
The mechanism of the sorting version is trivial and it is worth stating why it is not automatically the wrong answer. It is linear extra work, not quadratic, and for a single query on a moderate array it is almost always fast enough. The real issue is that the bound scales badly with n, and it reorders the input as a side effect unless you sort a copy.
The trade-off to name is what the interview is really testing. If k is small and the array is huge, the heap version wins because it never stores more than k items and its work per element is logarithmic in k rather than in n. If you will run many queries against the same array, sorting once and keeping the result is best. If you need the worst case to be good, quickselect with a random pivot or the median-of-three heuristic is the one to pick, because plain quickselect degrades to quadratic on adversarial input, and the heap version has a guaranteed bound if you prefer predictability.