Implement a Priority Queue from Scratch

viaLeetCode

Requirements: Implement a Priority Queue data structure from scratch (without using the language's built-in heap library), supporting insert and extract-min/extract-max operations.

Approach: Implement as a binary heap backed by a dynamic array.

  • insert: append the new element at the end, then "sift up" -- repeatedly swap it with its parent while it violates heap order.
  • extract-min/extract-max: swap the root with the last element, remove the last element, then "sift down" the new root -- repeatedly swap with the smaller/larger child while it violates heap order.

Both insert and extract run in O(log n) time; peek (read the root) is O(1).

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