Question presented to candidate: "Explain how Quickselect finds the kth smallest element of an unsorted list without sorting it, then implement it in Python. Also tell me how you would get the kth largest, and what its running time is."
What a strong answer should cover:
- The baselines:
sorted(nums)[k - 1]in O(n log n) and a heap in O(n log k). - Partition places the pivot at its final sorted index
p; Quickselect keeps only the side that contains the target index. kth largest is indexn - k. - Average O(n) (the
n + n/2 + n/4 + ...argument), worst case O(nยฒ), O(1) extra space when done in place. - Random pivots to avoid sorted-input worst cases, three-way partition for many duplicates, median of medians for a guaranteed O(n).
- Python specifics: tuple swaps, copying with
list(nums)so the caller's list is not reordered, a loop instead of recursion (the default recursion limit is 1000), andheapq.nsmallest/sortedas practical alternatives.
Code / implementation expected: Yes โ an iterative in-place quickselect(nums, k) with a Lomuto partition in Python.