← Questions

Queue with constant-time min and max

0
GoogleCoding

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) -> None adds val at the back.
  • dequeue() -> int removes and returns the front element.
  • get_min() -> int returns the smallest element currently in the queue, without removing it.
  • get_max() -> int returns 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_min or get_max raise?
  • Is amortized O(1) acceptable for dequeue as well as enqueue, or must it be worst-case?
  • With repeated values, must the min stay correct after one copy leaves (as in the example)?
  • Is a size or peek method 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding