Implement a Priority Queue

viaGlassdoor

Problem: Implement a priority queue from scratch, supporting insertion and extraction of the minimum (or maximum) element efficiently.

Constraints: Should support O(log n) insert and O(log n) extract-min/max.

Example: insert(5), insert(2), insert(8) -> extractMin() returns 2.

Approach: Implement as a binary heap backed by an array/list. Insert: append the new element at the end, then "bubble up" by repeatedly swapping with its parent while it violates the heap property. Extract-min/max: swap the root with the last element, remove the last element, then "sift down" from the root by swapping with the smaller/larger child until the heap property is restored. Both operations run in O(log n).

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account