DSA interview question
A task scheduler needs a priority queue where the smallest deadline always comes out first, and the platform has no standard library. Implement a binary min-heap over an array with:
insert(x)getMin()extractMin() (−1 if empty)size()deleteKey(i), which removes whatever element sits at heap index i, for example a cancelled taskInsertion sifts up, extraction moves the last element to the root and sifts down, and deleting index i puts the last element at i and sifts whichever direction is needed.
Example: insert(4), insert(2), extractMin() → 2, insert(6), deleteKey(0), extractMin() → 6, extractMin() → -1.
class MinHeap {
public:
void insert(int x);
int getMin() const; // -1 if empty
int extractMin(); // -1 if empty
void deleteKey(int i); // ignored if i is out of range
int size() const;
};
| Operations | Output | Explanation |
|---|---|---|
insert(4) insert(2) extractMin() insert(6) deleteKey(0) extractMin() extractMin() | 2 6 -1 | deleteKey(0) removes 4, the root at that moment |
insert(3) insert(1) insert(2) getMin() size() | 1 3 | |
extractMin() on an empty heap | -1 | |
insert(5) insert(5) extractMin() extractMin() | 5 5 | Duplicates |
insert(9) insert(7) insert(8) extractMin() extractMin() extractMin() | 7 8 9 | Sorted order out |
(Confirm: indices in deleteKey refer to positions in the heap's array; −1 signals "empty".)
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