PPractick

DSA interview question

Implement a Binary Min Heap

Medium · Data structures · Topics: heap

The problem

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:

Insertion 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.

Function signature

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;
};

Test cases

OperationsOutputExplanation
insert(4) insert(2) extractMin() insert(6) deleteKey(0) extractMin() extractMin()2 6 -1deleteKey(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 5Duplicates
insert(9) insert(7) insert(8) extractMin() extractMin() extractMin()7 8 9Sorted order out

(Confirm: indices in deleteKey refer to positions in the heap's array; −1 signals "empty".)

How interviewers phrase it

Clarifying questions to ask

  1. What should extractMin or getMin return on an empty heap? (−1.)
  2. Does deleteKey take an array index or a value? (An index.)
  3. Fixed capacity or growable? (Growable, using a vector.)

Follow-ups to expect

  1. "How does insert work?"
  2. "How does extractMin work?"
  3. "How do you delete an arbitrary index?"
  4. "How would you support 'decrease key by value'?"
  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