← All Exercises
Generic Priority Queue with a Comparator
advancedtypescript
Background
Typed priority queues appear in schedulers, event simulation, and graph algorithms where ordering logic varies by domain.
Problem
Implement a generic PriorityQueue class backed by a binary heap, supporting push, pop, peek, and size, then replay a list of operations and report the values returned by pop and peek.
Input
An array of operations, each ["push", value], ["pop"], or ["peek"], applied to a min-priority queue of numbers.
Output
An array of results: the value returned by each pop or peek, or the string "empty" when the queue is empty.
Sample tests
Sample 1
Input: ops = [["push",4],["push",2],["push",7],["pop"],["peek"],["pop"]]
Expected: [2,4,4]
Sample 2
Input: ops = [["pop"],["push",9],["peek"]]
Expected: ["empty",9]
Sample 3
Input: ops = [["push",5],["push",1],["push",3],["pop"],["pop"],["pop"],["pop"]]
Expected: [1,3,5,"empty"]
Your solution
Learning objective
Combine generics, comparator injection, and heap sift operations to build a reusable ordered container.