All problemsBack
Design Circular Queue
mediumDesign 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 bek.boolean enQueue(int value)inserts an element; returnstrueif successful.boolean deQueue()deletes an element from the front; returnstrueif successful.int Front()gets the front item, or-1if the queue is empty.int Rear()gets the last item, or-1if 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 themain harness and Run to verifyInput
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, 4Explanation: 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.