Question presented to candidate: "Given an unsorted list of integers and an integer k, return the kth largest element โ the kth in sorted descending order, not the kth distinct. Please solve it in Python, and tell me the trade-offs between the approaches you know."
What a strong answer should cover:
- Sorting first:
sorted(nums, reverse=True)[k - 1], O(n log n). - A min-heap of size k with
heapq: push, pop when the size exceeds k, answer isheap[0]; O(n log k) time, O(k) space; why a min-heap. - Quickselect at index
n - k: O(n) average, O(nยฒ) worst case, in place on a copy. - When to choose which: streams and small k favour the heap; one-off in-memory queries favour Quickselect.
- Python specifics:
heapqis a min-heap only (negate values for a max-heap),heapq.heappushpop,heapq.nlargest(k, nums)[-1], and that the heap list is not sorted.
Clarifying questions expected:
- "Do duplicates count separately?"
- "Is the data a stream or a list in memory?"
Code / implementation expected: Yes โ at least the heapq solution in Python; ideally also Quickselect.