Back

Design Circular Queue

medium

Design your implementation of a circular queue. A circular queue is a linear data structure in which operations are performed based on the FIFO principle, and the last position is connected back to the first position to make a circle.

Implement the MyCircularQueue class:

  • MyCircularQueue(k) initializes the object with the size of the queue to be k.
  • boolean enQueue(int value) inserts an element; returns true if successful.
  • boolean deQueue() deletes an element from the front; returns true if successful.
  • int Front() gets the front item, or -1 if the queue is empty.
  • int Rear() gets the last item, or -1 if the queue is empty.
  • boolean isEmpty() / boolean isFull() check the queue's state.

You must implement every function in O(1) time.

Test Cases

Copy an input into the main harness and Run to verify
Input
MyCircularQueue(3), enQueue(1), enQueue(2), enQueue(3), enQueue(4), Rear(), isFull(), deQueue(), enQueue(4), Rear()
Expected Output
true, true, true, false, 3, true, true, true, 4

Explanation: The fourth enQueue fails because the queue is full; after one deQueue there is room again.

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls will be made to each method.

Hints

Hint 1 — click to reveal

A fixed array plus a head index and a count avoids any shifting.

Hint 2 — click to reveal

Wrap indices with modulo arithmetic rather than moving elements.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.