Implement a circular queue
Standard · Write code · about 15 min
Complete CircularQueue, a queue of at most k values stored in a fixed array whose indices wrap around. Every operation must be O(1); do not shift values.
enqueue(x)adds x at the rear and returns true, or returns false when the queue is full.dequeue()removes and returns the front value, or -1 when empty.front()andrear()return the oldest and newest value, or -1 when empty.
The given circularQueue(k, ops) collects one result per operation (enqueue: 1 or 0).
Example 1
Input:
[3,["enqueue 1","enqueue 2","enqueue 3","enqueue 4","rear","dequeue","enqueue 4","rear","front"]]
Output:
[1,1,1,0,3,1,1,4,2]
enqueue 4 fails while all 3 slots are full. After one dequeue it fits in the freed slot 0.
Example 2
Input:
[2,["dequeue","enqueue 7","front","rear","dequeue","front"]]
Output:
[-1,1,7,7,7,-1]
Constraints
- 1 ≤ k ≤ 1, 000
- 1 ≤ ops.length ≤ 1, 000
- Each op is "enqueue x" with 0 ≤ x ≤ 1, 000, "dequeue", "front" or "rear"
Learn the idea first: Queues: enqueue, dequeue; circular buffer, a visual lesson.
More Queues: enqueue, dequeue; circular buffer problems
- Which value leaves first? Warm-up
- Predict head and tail Warm-up
- Number of recent calls Standard
- Spot the bug: the tail runs off the end Standard
- Moving average from a stream Challenge