Deque with Minimum
Deque with Minimum
Task
Implement a deque that supports operations:
push_front(x)— add to the frontpush_back(x)— add to the backpop_front()— remove from the frontpop_back()— remove from the backget_min()— get the minimum element
Idea: keep two structures (two MinStacks), but instead of “pouring everything like in a queue”
we rebalance when one of the parts becomes empty (make the sizes approximately equal).
Idea
Store the deque as two parts:
L(left) — elements closer to the front of the deque (stack top = front)R(right) — elements closer to the back of the deque (stack top = back)
Then:
frontis on the top ofLbackis on the top ofR- deque minimum =
min(L.min, R.min)
If we need to remove from a side but the corresponding stack is empty:
- collect all elements in the correct order,
- split in half,
- put them back so that the sizes of
LandRare close.