Question

Can one build a priority queue using stacks, such that the priority queue has the same complexity for each operation. Could it be done? If so how? If not what is the best solution that can be done?

Each operation of a stack using an array is $O(1)$ whereas almost all operation of priority queue is $O(logn)$. an implementation can be done using $2D$ stacks, each elements of the stack is again a stack. When the first element of the main stack is the first element of the other stacks. The dequeue operation will take $O(n)$ as it is LIFO and the priority queue is FIFO.

Was it helpful?

Solution

Think about it. You can sort an array by adding all the items to a priority queue, then removing the items in sorted order.

If you could run a priority queue in constant time, you could sort in linear time. But you can't.

Licensed under: CC-BY-SA with attribution
Not affiliated with cs.stackexchange
scroll top