Queue Using an Array

Bounded Ring Buffer

Build a first-in, first-out queue on top of a fixed-size array so that enqueue, dequeue and peek all run in constant time and no slot is ever wasted.

Overview

A queue takes items at the back and gives them out at the front, in the order they arrived. The question asks you to build one on a plain array of fixed size. It sounds like a warm-up, and it is, but the interviewer is watching for one insight: a queue on a straight array leaks slots, and the fix is to treat the array as a ring.

The design also shows whether you can hide the mechanism behind a small, clean interface. Callers should see enqueue, dequeue, peek, is_empty, is_full and len, and nothing about indexes. A strong answer states the ring idea in the first minute, writes the modulo formula once, and tests the wrap-around case out loud.

Why a straight array leaks

Suppose the front index moves forward on every dequeue and the rear index moves forward on every enqueue. Slots behind the front are dead: nothing will ever be written there again. Trace it on an array of capacity 4.

  • Enqueue a, b and c. The array is 'a b c .', front is 0 and rear is 3, so 1 slot can still be used.
  • Dequeue twice. The array is '. . c .', front is 2 and rear is 3. Still only 1 slot can be used, because the two freed slots sit behind the front.
  • Enqueue d. The array is '. . c d', front is 2 and rear is 4, so 0 slots are left.
  • Enqueue e. There is no room: 0 usable slots, with two empty slots in the array.

After step 4 the queue holds two items in an array of four and still reports full. Shifting everything to the front on each dequeue would fix that at O(n) per call, which defeats the point of a queue.

Functional requirements

  • enqueue(item) adds at the back; on a full queue it raises, and try_enqueue returns False instead
  • dequeue() removes and returns the front item; on an empty queue it raises, and try_dequeue returns None instead
  • peek() returns the front item without removing it
  • is_empty(), is_full() and len() report the state without touching the items
  • Iterating the queue yields items from front to back, in logical order, whatever the physical layout

Non-functional requirements

  • Every operation is O(1); nothing is ever shifted
  • Memory is one array of the given capacity, allocated once
  • A slot is reused as soon as the item in it has been dequeued, so any number of cycles fits
  • Indexes and the array are private; callers never see them

Interview questions

  • Why not shift the items forward on every dequeue and keep a plain array?
  • The queue is full. How would you let it grow?
  • Should dequeue on an empty queue raise, or return None?
  • Several threads share the queue. What changes?
  • What bugs show up in this problem, and how do you test for them?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio