Queue with constant-time min and max
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google. It tests queue, monotonic deque and design.
Implement a FIFO queue of integers that can also report its smallest and largest element at any time.
Implement the MinMaxQueue class:
-
MinMaxQueue()creates an empty queue. -
enqueue(val: int) -> Noneaddsvalat the back. -
dequeue() -> intremoves and returns the front element. -
get_min() -> intreturns the smallest element currently in the queue, without removing it. -
get_max() -> intreturns the largest element currently in the queue, without removing it.
Calling dequeue, get_min or get_max on an empty queue should raise an error.
Constraints
- Every operation must run in O(1) time (amortized O(1) is acceptable for
enqueue). - Values may repeat and may be negative.
- Up to 10^5 operations in total.
Example
q = MinMaxQueue()
q.enqueue(6); q.enqueue(2); q.enqueue(9); q.enqueue(2)
q.get_min() -> 2
q.get_max() -> 9
q.dequeue() -> 6
q.dequeue() -> 2
q.get_min() -> 2 # the second 2 is still queued
q.dequeue() -> 9
q.get_max() -> 2
Start by describing the simple approach, then make all queries constant time.
Clarifying questions
- Which error should an empty
dequeue,get_minorget_maxraise? - Is amortized
O(1)acceptable fordequeueas well asenqueue, or must it be worst-case? - With repeated values, must the min stay correct after one copy leaves (as in the example)?
- Is a
sizeorpeekmethod needed?
What a strong answer covers
- Names the simple approach first (scan the queue on each query,
O(n)) and why a single min variable breaks on dequeue. - Keeps two monotonic deques beside the main queue: one non-decreasing for the min, one non-increasing for the max. On enqueue, pop strictly larger (or smaller) values from the back; on dequeue, pop the front of a monotonic deque when it equals the removed value.
- Keeps equal values in the monotonic deques so duplicates are handled, and explains the amortized
O(1)bound (each value enters and leaves each deque once). - Mentions the alternative: a queue built from two stacks, each entry storing the running min and max.
- Tests the example's duplicate
2, empty-queue errors, and a strictly increasing then decreasing run.
Follow-ups
- Make every operation worst-case
O(1). - Add
get_median(). - Use the structure to report the max of every window of size
k.
Where it's asked
What it tests
queue · monotonic deque · design
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
