Skip to the solution
MediumDSAAmazonAsked in 2024, 2023, 202211 min read

Find the kth largest element in an array

808 views

The problem

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 is heap[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: heapq is 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.

  • dsa
  • heap
  • arrays

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

11 min read ยท 14 sections

Python code

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

PythonSort vs size-k heap vs selection on six inputs
PythonWatch the size-3 heap on a stream, and duplicates vs distinct values

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 64 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

How do you generate all permutations of an array?

Continue