Circular queue
A queue in a fixed-size array that wraps around to the start when it reaches the end; each enqueue and dequeue is O(1) and no space goes to waste.
A queue in a plain array has a problem: each dequeue at the front leaves an empty slot at the start of the array. A circular queue treats the array as a ring: after the last slot comes the first. So:
Read the full explanation ↓- Time:
O(1) per operation - Space:
O(capacity) - Horowitz–Sahni, chapter 3
- CLRS, section 10.1
Positive numbers are ENQUEUE and 0 means DEQUEUE; after some enqueues and dequeues, rear wraps from slot 4 to slot 0.
def circular_queue(ops):# A positive number is enqueued; 0 dequeues. The queue lives in a fixed array of 5 slots.cap = 5buf = [None] * capfront = 0rear = 0size = 0out = []for op in ops:if op > 0:if size == cap:continuerear = (front + size) % capbuf[rear] = opsize = size + 1else:if size == 0:continueout.append(buf[front])buf[front] = Nonefront = (front + 1) % capsize = size - 1return out
Start
Local variables
Orange = changed in this step
ops list
Call stack
- circular_queue()line 1
Explanation
The idea
A queue in a plain array has a problem: each dequeue at the front leaves an empty slot at the start of the array. A circular queue treats the array as a ring: after the last slot comes the first. So:
rear = (front + size) mod cap
front = (front + 1) mod cap (after a dequeue)
Full or empty?
With only front and rear, front = rear could mean full or empty. Here size is kept separately; Horowitz–Sahni
always leave one slot empty to avoid the ambiguity instead.
The input
A positive number means ENQUEUE that number, and 0 means DEQUEUE. The capacity is 5.