Queue with Minimum
Queue with Minimum
Task
Implement a queue that supports three operations:
push(x)— add an element to the endpop()— remove an element from the beginningget_min()— get the minimum element
All operations must work in O(1) amortized time.
Idea
A queue can be implemented using two stacks:
in— a stack for adding elementsout— a stack for removing elements
If both stacks can maintain a minimum (MinStack),
then the minimum of the entire queue is:
How it works
Insertion (push)
Add the element to the in stack.
Deletion (pop)
If the out stack is empty:
- move all elements from
intoout - during the move, the order is automatically reversed
After that, remove the element from out.
Getting the minimum (get_min)
- if one stack is empty — take the minimum from the other
- if both are not empty — take the minimum of the two