Implement Queue using Arrays
Implement Queue using Arrays is a GFG problem (Easy). Build a class myQueue(n) whose storage is an array of size n:
enqueue(x)addsxat the rear;dequeue()removes the front element.getFront()andgetRear()return the front and rear elements, or −1 when the queue is empty.isEmpty()andisFull()say whether the queue holds 0 ornelements.
A dequeue or a read can arrive while the queue is empty, and an enqueue while it is full; those calls must leave the queue unchanged.
- 1 <= n <= 10³ (array size)
- 1 <= number of queries <= 10³
- 0 <= x <= 10⁵
Intuition
A queue adds at the rear and removes at the front, so both ends keep moving right. Shifting every element left after a dequeue keeps the front at index 0 but costs O(n) per call. Letting the front index move right is O(1), yet the freed slots at the start are never used again.
Treat the array as a ring instead: after the last slot comes slot 0. Keep front, the index of the oldest element, and size, how many are stored. The next free slot is (front + size) % n and the rear is one before it, so every method is a little index arithmetic and no element ever moves.
A fixed-size array that must serve as a queue for an unlimited number of calls means a circular buffer: indices that wrap with % n, plus a count so that full and empty can be told apart.
Approach
Before reading on, take n = 3: enqueue 1, 2, 3, dequeue twice, then enqueue 4. Decide which index 4 should be written to, and what formula gives that index.
Store front and size, not front and rear
Set front = 0 and size = 0. If you kept two indices instead, a full ring and an empty ring would leave them in the same relative position. With size, empty is size == 0 and full is size == n, and no slot has to be kept free to tell them apart.
Enqueue at (front + size) % n
If the queue is full, return. Otherwise write x at (front + size) % n and add 1 to size. Once that position passes the last index, the % n sends it back to slot 0, reusing a slot that an earlier dequeue freed.
Dequeue by moving front forward
If the queue is empty, return. Otherwise set front = (front + 1) % n and subtract 1 from size. The old value stays in the array, but it is now outside the stored range and the next enqueue that reaches its slot writes over it.
Read both ends from front and size
getFront() returns arr[front] and getRear() returns arr[(front + size - 1) % n], each −1 when size is 0. The rear is the last slot written, one before the next free slot, and it needs the same wrap.
Code in Python, C++ and Java
front is 0 and size is 0. There is no rear index to keep: it is always worked out from these two.size equals the array length, so every slot is in use: true. Here front and rear sit next to each other on the ring.front moves to slot 1 and size drops to 2. The 1 stays in the array, faded, until an enqueue writes over it.front moves to slot 2 and size drops to 1. The 2 stays in the array, faded, until an enqueue writes over it.front = 2, so getFront returns 3.size equals the array length, so every slot is in use: true. Here front and rear sit next to each other on the ring.front is 0 and size is 0. There is no rear index to keep: it is always worked out from these two.size is 0, so there is no rear element; the rule is to return −1.size equals the array length, so every slot is in use: true. Here front and rear sit next to each other on the ring.front moves to slot 1 and size drops to 1. The 3 stays in the array, faded, until an enqueue writes over it.front moves to slot 0, wrapping past the end and size drops to 0. The 7 stays in the array, faded, until an enqueue writes over it.size is 0, so the answer is true, whatever the faded values in the array say.size would go to −1 and every later answer would be wrong.size is 0, so there is no front element; the rule is to return −1.Common pitfalls
Letting the rear index run off the end
if self.rear == len(self.arr):
return
self.arr[self.rear] = x
self.rear += 1if self.isFull():
return
rear = (self.front + self.size) % len(self.arr)
self.arr[rear] = x
self.size += 1Without the wrap, slots freed by dequeue are never reused. With n = 2: enqueue 3, enqueue 7, dequeue, dequeue. The queue is empty, but the rear index is 2, so enqueue 5 is refused as if the queue were full.
Telling empty from full with front == rear
def isEmpty(self):
return self.front == self.reardef isEmpty(self):
return self.size == 0With a wrapping rear index that points at the next free slot, filling the array brings the rear all the way round to the front. With n = 2, enqueue 3 and enqueue 7 leave front == rear, and this reports the full queue as empty.
Reading the rear at the next free slot
return self.arr[(self.front + self.size) % len(self.arr)]
return self.arr[(self.front + self.size - 1) % len(self.arr)]
(front + size) % n is where the next enqueue will write, one past the newest element. With n = 3, enqueue 5 and enqueue 3, then getRear returns 0 from the unused slot 2 instead of 3.
Complexity
n slots is allocated once.Implement Queue using Arrays FAQ
Why not shift the elements left on each dequeue?
It works, and it keeps the front at index 0 so no wrap is needed. But every dequeue then copies all remaining elements: filling a 1,000-slot queue and emptying it moves about 500,000 values, while the ring moves none.
Is a stack on an array built the same way?
It is simpler. A stack adds and removes at the same end, so Implement Stack using Arrays needs a single top index and never wraps around.
Can a queue be built without an array?
Yes. A linked list with head and tail pointers never fills up, and Implement Queue using Stacks builds one out of two stacks, paying for reordering only when the output stack runs dry.