Smart Mock Interview Logo
Get Started
Concurrent Priority Queue
Created by Smart Mock Interview

Interview Questions

  1. Implement a data structure called ConcurrentPriorityQueue
    coding

    Problem:

    Implement a data structure called ConcurrentPriorityQueue that supports the following operations efficiently in a multi-threaded environment:

    • push(item, priority): Adds an item to the queue with a given priority. Lower priority values indicate higher priority (i.e., they should be dequeued first).
    • pop(): Removes and returns the highest priority item from the queue. If the queue is empty, it should return null.
    • peek(): Returns the highest priority item without removing it. If the queue is empty, it should return null.
    • size(): Returns the number of elements in the queue.

    Your implementation should ensure thread safety, meaning multiple threads can concurrently call push, pop, peek, and size without causing data corruption or race conditions. You can use JavaScript's built-in synchronization primitives (e.g., Atomics, SharedArrayBuffer, or libraries that provide mutexes/locks) to achieve this.

    Sample Input:

    onst queue = new ConcurrentPriorityQueue();

    // Thread 1 queue.push("A", 3); queue.push("B", 1);

    // Thread 2 queue.push("C", 2);

    // Thread 1 const highestPriority = queue.pop();

    // Thread 2 const size = queue.size();

    Sample Output:

    highestPriority = "B" size = 2 // or 1, depending on timing of the threads.

    Constraints:

    • Priorities are integers.
    • The queue should handle an arbitrary number of items.
    • The implementation should be optimized for concurrent access (minimize contention).
    • Error handling for invalid input is not required.