Design Circular Queue
MediumP2Coding
Design a circular queue of fixed capacity k backed by a single array of size k. The last position connects back to the first, so freed slots at the front are reused.
Implement the MyCircularQueue class:
MyCircularQueue(k)sets the capacity.enQueue(value)adds at the rear; returnstrueon success,falseif the queue is full.deQueue()removes from the front; returnstrueon success,falseif the queue is empty.Front()returns the front value, or-1if empty.Rear()returns the rear value (the most recently added still in the queue), or-1if empty.isEmpty()andisFull()report the state.
Every operation is O(1). Do not use a resizable list as the queue itself.
Example 1
- Input
- ["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"] [[3],[1],[2],[3],[4],[],[],[],[4],[]]
- Output
- [null,true,true,true,false,3,true,true,true,4]
- Why
- After the dequeue a slot is free, so the next enQueue wraps around and succeeds.
Constraints
- 1 <= k <= 1000
- 0 <= value <= 1000
- At most 3000 calls.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.