PPractick

DSA interview question

Kth Smallest Element (Using a Priority Queue)

Medium · Data structures · Topics: heap, priority queue

The problem

A delivery app wants the k-th fastest delivery time of the day to set a realistic promise for customers. Sorting all times is O(n log n). Keeping a max-heap of the k smallest times seen so far is O(n log k): its root is the largest of those k, which is exactly the k-th smallest. Any new time smaller than the root replaces it. It's the mirror image of the k-th largest problem.

Example: [7, 10, 4, 3, 20, 15], k = 3 → 7.

Function signature

int kthSmallest(const vector<int>& arr, int k);  // 1 <= k <= n

Test cases

Input (arr, k)OutputExplanation
([7, 10, 4, 3, 20, 15], 3)7Sorted: 3, 4, 7, …
([7, 10, 4, 20, 15], 4)15
([1], 1)1
([5, 5, 5, 1], 2)5Duplicates count
([2, -1, 0], 1)-1The minimum

(Confirm: k-th smallest counting duplicates; 1 ≤ k ≤ n.)

How interviewers phrase it

Clarifying questions to ask

  1. Counting duplicates? (Yes.)
  2. Is k always valid?
  3. Can I modify the array? (If so, quickselect is an option.)

Follow-ups to expect

  1. "Why a max-heap?"
  2. "Why not a min-heap of everything?"
  3. "When is the size-k heap better?"
  4. "Quickselect?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in