← All Exercises

Min-Heap Priority Queue with Stable Ties

advancedjavascript~15min

Background

Priority queues power schedulers, Dijkstra's algorithm, and event loops. Binary heaps give O(log n) insertion and removal, but tie-breaking needs an extra sequence number to stay deterministic.

Problem

Implement class MinHeap with push(item, priority), pop(), and peek(). pop returns the smallest priority and removes it; equal priorities must be returned in insertion order (stable). Empty pop and peek return null. Process an ops array containing push, pop, and peek commands and report the popped items plus the final peek.

Input

A JSON object with ops, where each op is push (item, priority), pop, or peek.

Output

A JSON object with popped (labels in pop order, null for empty pops) and peek (item and priority, or null).

Sample tests

Sample 1

Input: {"ops":[{"op":"push","item":"a","priority":5},{"op":"push","item":"b","priority":1},{"op":"push","item":"c","priority":3},{"op":"pop"},{"op":"push","item":"d","priority":1},{"op":"pop"},{"op":"pop"},{"op":"peek"}]}
Expected: {"popped":["b","d","c"],"peek":{"item":"a","priority":5}}

Sample 2

Input: {"ops":[{"op":"push","item":"x","priority":1},{"op":"push","item":"y","priority":1},{"op":"push","item":"z","priority":1},{"op":"pop"},{"op":"pop"},{"op":"pop"},{"op":"peek"}]}
Expected: {"popped":["x","y","z"],"peek":null}

Sample 3

Input: {"ops":[{"op":"pop"},{"op":"push","item":"only","priority":2},{"op":"peek"}]}
Expected: {"popped":[null],"peek":{"item":"only","priority":2}}

Your solution

Learning objective

Understand heap operations, sift-up and sift-down correctness, and stable ordering for scheduler queues.