AlgoMaster Logo
AlgoMasterDesign Concurrent Priority Queuemedium

Design Concurrent Priority Queue

medium

Design a thread-safe min-priority queue for integers. Multiple producer and consumer threads share one ConcurrentPriorityQueue instance.

Implement the following operations:

  • put(value) inserts value into the queue.
  • take() removes and returns the smallest value. If the queue is empty, it must block until a value becomes available.
  • peek() returns the smallest value without removing it, or -1 when the queue is empty.
  • size() returns the current number of values.

Every public operation must be thread-safe. Concurrent inserts must not corrupt the heap, each inserted value must be removed exactly once, and waiting consumers must resume when producers add values.

The judge creates all producer and consumer threads. Your class should provide synchronization around the shared heap rather than create worker threads itself.

The judge also preloads the standard concurrency and collection APIs for every supported language. You do not need to add import, include, using, or package statements.

Example 1:

Input:

Output:

Explanation: peek observes 1 without removing it. The three take calls then return the values in ascending priority order.

Example 2:

Input:

Output:

Explanation: Inserting 42 wakes the blocked consumer, which removes and returns it.

Constraints

  • 0 <= value <= 1_000_000
  • At most 10_000 values are stored at once.
  • put, take, peek, and size may be called concurrently.
  • The judge eventually supplies enough values for every blocked take call.
  • Duplicate values are allowed.
Loading...

Input

put(5)
put(1)
put(3)
peek()
take()
take()
take()

Output

[1, 1, 3, 5]

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.