~/problems / Linked lists / Linked lists

Design Circular Queue

medium ~25 min

A print server keeps waiting jobs in a first-in, first-out queue that can never hold more than a fixed number of jobs. Build the class BoundedQueue:

  • BoundedQueue(capacity) creates an empty queue that holds at most capacity values (capacity >= 1).
  • enqueue(value) -> bool adds value at the back and returns True, or returns False and changes nothing if the queue is full.
  • dequeue() -> int removes and returns the value at the front, or returns -1 if the queue is empty.
  • front() -> int and back() -> int return the value at the front / back without removing it, or -1 if the queue is empty.
  • size() -> int returns how many values are waiting.
  • is_full() -> bool returns whether size() == capacity.
q = BoundedQueue(2)
q.enqueue(5)     # True
q.enqueue(8)     # True
q.enqueue(1)     # False   (full)
q.is_full()      # True
q.dequeue()      # 5
q.enqueue(1)     # True
q.front()        # 8
q.back()         # 1
q.size()         # 2
q.dequeue()      # 8
q.dequeue()      # 1
q.dequeue()      # -1
q.back()         # -1

Constraints: capacity <= 200,000; values are integers from 0 to 10^9; up to 600,000 calls. Every method must run in O(1) time and the queue should use O(capacity) memory however many values pass through it. Removing from the front of a Python list (pop(0), del q[0]) shifts every other element, so it is too slow here. Don't use collections.deque or the queue module: the point is to build the structure yourself.

Show hint

Either chain the values together as nodes with a pointer to each end, or keep a fixed-size array with an index for the front and a count, letting positions wrap past the end back to the start.

Topic: Linked lists. Dummy heads, pointer rewiring, fast/slow pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc