Skip to the solution
MediumDSA11 min read

How does Quickselect find the kth smallest/largest element?

1.1k views

The problem

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 index n - 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), and heapq.nsmallest / sorted as practical alternatives.

Code / implementation expected: Yes โ€” an iterative in-place quickselect(nums, k) with a Lomuto partition in Python.

  • quickselect
  • 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 ยท 13 sections

Python code

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

PythonQuickselect for the kth smallest and kth largest on eight inputs
PythonTrace every partition round and check against a sorted copy
PythonCount comparisons: last-element pivot vs random pivot vs three-way partition

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 47 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 implement a queue using two stacks?

Continue