Skip to the code
cf.
+25 XP

#379 Build a Job Heap

medium

Your app's background worker needs a priority queue for jobs, where a smaller number means a more urgent job. JavaScript has no built-in heap, so you'll write one.

Write a class JobHeap with:

  • constructor(): starts empty.
  • push(priority): adds a number. Returns nothing.
  • pop(): removes and returns the smallest number, or null if empty.
  • peek(): returns the smallest number without removing it, or null if empty.
  • size(): returns how many numbers are stored.

Each push and pop should take O(log n) time, so don't sort the whole list on every call.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new JobHeap(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["JobHeap","push","push","push","peek","pop","pop","size"]
[[],[5],[1],[3],[],[],[],[]]
Output: [null,null,null,null,1,1,3,1]

The smallest is always returned first: 1, then 3. Only 5 is left.

Example 2

Input: ["JobHeap","pop","peek","size"]
[[],[],[],[]]
Output: [null,null,null,0]

An empty heap returns null for pop and peek.

Constraints

  • At most 10^4 calls.
  • -10^6 <= priority <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).