Skip to the solution
MediumDSA16 min read

How do you find the Kth largest element — heap vs quickselect, and when to choose which?

153 views

The problem

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: heapq is a min-heap, which is exactly what this needs; heapq.heapreplace / heappushpop do 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.

  • heap
  • quickselect
  • Google

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

16 min read · 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonKth largest: size-k min-heap and random-pivot quickselect on six inputs
PythonCounting the work: heap entries, quickselect comparisons, worst cases

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 120 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Longest consecutive sequence in O(n) with hash set — why not sort?

Continue