Design Circular Queue
On this page
Problem statement
Implement a queue with a fixed capacity k on top of an array, reusing slots as items leave. Support
enQueue(value)(false if full),deQueue()(false if empty),Front()andRear()(−1 if empty),isEmpty()andisFull(), all in O(1) time without moving elements.
The ring buffer behind this question is everywhere in real systems: network card queues, log buffers, audio streams, producer/consumer pipelines. That is why it is often followed by "now make it thread-safe". Original problem: LeetCode 622.
Example

MyCircularQueue(3)
enQueue(1) -> true; enQueue(2) -> true; enQueue(3) -> true
enQueue(4) -> false # full
Rear() -> 3
deQueue() -> true # removes 1
enQueue(4) -> true # goes into slot 0
Front() -> 2
Rear() -> 4
Constraints (assumed)
- 1 ≤ k ≤ 1,000; up to 3,000 calls; values are non-negative (so −1 can mean "empty").
What this question tests
- Modular arithmetic for wrapping indices.
- Choosing a state (head + count, or head + tail) that tells "empty" and "full" apart.
- Clean API design and, as a follow-up, thread safety.
Questions to ask first
- What should operations return when they fail? (Here: false, or −1 for Front/Rear on empty.)
- Can I use a built-in deque? (No; the point is the array.)
- Will several threads use it? (Here: no; the blocking version is a follow-up.)
- Should a full queue overwrite the oldest item instead? (Here: no. That is the "ring buffer for logs" variant.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.