Question presented to candidate: "Given an unsorted list of integers and a number k, return the kth largest element — duplicates count, so it is the kth element in sorted descending order. Write it in Python. Then tell me: would you use a heap or quickselect, and when would you choose the other one?"
What a strong answer should cover:
- The baseline: sort and index
a[n - k], O(n log n). - A min-heap of size k (the root is the gatekeeper): O(n log k) time, O(k) space, works on a stream and never modifies the input.
- Quickselect: partition, keep only the side holding index n − k; average O(n), worst case O(n²); random pivot, and a three-way partition for duplicates.
- The decision: quickselect for a one-off in-memory query; the heap for streams, huge or read-only data, small k, or a guaranteed bound; sort once for many queries.
- Python specifics:
heapqis a min-heap, which is exactly what this needs;heapq.heapreplace/heappushpopdo pop-and-push in one sift;heapq.nlargest(k, nums)[-1]is the one-liner; write quickselect iteratively because the default recursion limit is 1000.
Clarifying questions expected:
- Do duplicates count separately, and is k 1-based?
- Can I modify the input list, and does the data fit in memory?
Code / implementation expected: Yes — the size-k heapq solution, and quickselect with a random pivot in Python.