TRT
Sign in
mediumFoundationsLeetCode#ring buffer#head and size

Design circular queue

Implement a fixed-size queue on a ring buffer, with every operation in O(1) and correct full and empty checks.

The Runtime Theory Team1 min read
Taught inQueues and ring buffersA queue serves items in the order they arrived. Built on a ring buffer, a fixed array whose start and end wrap around, every operation is O(1) and no item ever moves.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ink = 3; enQueue(1), enQueue(2), enQueue(3), enQueue(4)

outtrue, true, true, false

inthen Rear(), isFull(), deQueue(), enQueue(4), Rear()

out3, true, true, true, 4

ink = 1; deQueue() on an empty queue

outfalse

Implement MyCircularQueue(k) with enQueue, deQueue, Front, Rear, isEmpty and isFull, using a fixed array of k slots.

Before you code

Store head and size, not head and tail, and compute everything else with the remainder. Then "full" and "empty" are just size == k and size == 0, with no ambiguity.

Hints

  1. enQueue: if full, return False; otherwise write at (head + size) % k and increment size.
  2. deQueue: if empty, return False; otherwise advance head = (head + 1) % k and decrement size.
  3. Rear is the item at (head + size - 1) % k.
  4. Test the wrap-around: fill, remove one, add one, and check Rear.

Production & complexity notes

When solving Design circular queue on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Queues and ring buffers to reinforce the underlying pattern.

What it practices

Head, size and wrap-around, from Queues and ring buffers.

Not started

Sign in to save your learning progress.

Sign in to save