GeeksforGeeks » Algorithms
Find min() in queue
(4 posts)-
Modify queue data structure to support enqueue() , dequeue() , findmin() .... Is it possible to do this in O(1) with extra space ?
-
One solution is the "monotonic wedge". Another solution is to use two stacks that support findMin. One stack is the input stack and the other is the output stack. When we push onto the queue, we push onto the input stack. When we pop off the queue, we pop off the output stack. If the output stack is empty, we have to pop items from the input stack and push them onto the output stack. The minimum element in the queue is the minimum element in both stacks. Since each element is pushed/poped exactly once from both stacks, this is O(1) for push/pop for the queue. Since findMin is O(1) for both stacks, this is O(1) for the queue.
There are plenty of solutions for how to do a stack with O(1) findMin.
-
I was a bit lazy when I wrote that. But there are plenty of descriptions on how to build a queue from two stacks and how to implement a stack with O(1) findMin. Basically just combine the two to get a queue with findMin in O(1).
Reply
You must log in to post.