The Monotonic Queue is a data structure that maintains a sequence of numbers by maintaining
This requires space.
Lemma
Let .
Push
Push updates to in amortized time and space.
Algorithm
Lemma
Let , then
Applying the lemma to find yields an algorithm that solves the problem in amortized time and space.
void push(int x) {
while (!q.empty() && q.back().second < x) {
q.pop_back();
}
q.emplace_back(r++, x);
}Proof
Pop
Pop updates to in amortized time and space.
Algorithm
Lemma
Let , then
Applying the lemma to find yields an algorithm that solves the problem in amortized time and space.
void pop() {
if (q.front().first == l++) {
q.pop_front();
}
}Proof
Top
Top finds in amortized time and space.
Algorithm
Lemma
Applying the lemma to find yields an algorithm that solves the problem in amortized time and space.
int top() {
return q.front().second;
}Proof