Skip to content

Instantly share code, notes, and snippets.

@kartikkukreja
Created October 27, 2016 20:07
Show Gist options
  • Save kartikkukreja/fcb748f29bc044a8076a09c8d9969e63 to your computer and use it in GitHub Desktop.
Save kartikkukreja/fcb748f29bc044a8076a09c8d9969e63 to your computer and use it in GitHub Desktop.
Queue with min operation using deque
template <typename T>
class QueueWithMin {
private:
queue<T> Q;
deque<T> D;
public:
void enqueue(T& x) {
Q.push(x);
while (!D.empty() && D.back() > x)
D.pop_back();
D.push_back(x);
}
T dequeue() {
if (Q.empty())
throw "queue empty";
if (D.front() == Q.front())
D.pop_front();
T top = Q.front(); Q.pop();
return top;
}
T getMin() {
return D.front();
}
int size() {
return Q.size();
}
bool empty() {
return Q.empty();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment