Interview Questions
- Implement a data structure called
ConcurrentPriorityQueuecodingProblem:
Implement a data structure called
ConcurrentPriorityQueuethat supports the following operations efficiently in a multi-threaded environment:push(item, priority): Adds anitemto the queue with a givenpriority. 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 returnnull.peek(): Returns the highest priority item without removing it. If the queue is empty, it should returnnull.size(): Returns the number of elements in the queue.
Your implementation should ensure thread safety, meaning multiple threads can concurrently call
push,pop,peek, andsizewithout 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.