DSA interview question
A game server keeps a live high-score board and must report the k-th highest score after every new score arrives: it's the cutoff for the top-k badge. Re-sorting after each score is wasteful. Keep a min-heap of the k largest scores seen so far. Its root is the k-th largest. A new score enters only if it beats the root (or the heap has fewer than k scores), and then the root is evicted. Each update costs O(log k).
Example: KthLargest(3, [4, 5, 8, 2]): add(3) → 4, add(5) → 5, add(10) → 5, add(9) → 8, add(4) → 8.
class KthLargest {
public:
KthLargest(int k, const vector<int>& nums);
int add(int val); // returns the k-th largest after adding val
};
| Operations | Output | Explanation |
|---|---|---|
KthLargest(3, [4,5,8,2]), add 3, 5, 10, 9, 4 | 4 5 5 8 8 | LeetCode's example |
KthLargest(1, []), add −3, −2, −4, 0, 4 | -3 -2 -2 0 4 | k = 1 is the running maximum |
KthLargest(2, [0]), add −1, 1, −2, −4, 3 | -1 0 0 0 1 | Starts with fewer than k elements |
(Confirm: after every add there are at least k elements in total; duplicates count separately.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in