GeeksforGeeks Easy

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) adds x at the rear; dequeue() removes the front element.
  • getFront() and getRear() return the front and rear elements, or −1 when the queue is empty.
  • isEmpty() and isFull() say whether the queue holds 0 or n elements.

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.

Constraints
  • 1 <= n <= 10³ (array size)
  • 1 <= number of queries <= 10³
  • 0 <= x <= 10⁵
queuedesign
Open on GeeksforGeeks ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class myQueue:
▶2 def __init__(self, n):
▶3 self.arr = [0] * n
▶4 self.front = 0
▶5 self.size = 0
▶6 
▶7 def isEmpty(self):
▶8 return self.size == 0
▶9 
▶10 def isFull(self):
▶11 return self.size == len(self.arr)
▶12 
▶13 def enqueue(self, x):
▶14 if self.isFull():
▶15 return
▶16 rear = (self.front + self.size) % len(self.arr)
▶17 self.arr[rear] = x
▶18 self.size += 1
▶19 
▶20 def dequeue(self):
▶21 if self.isEmpty():
▶22 return
▶23 self.front = (self.front + 1) % len(self.arr)
▶24 self.size -= 1
▶25 
▶26 def getFront(self):
▶27 if self.isEmpty():
▶28 return -1
▶29 return self.arr[self.front]
▶30 
▶31 def getRear(self):
▶32 if self.isEmpty():
▶33 return -1
▶34 return self.arr[(self.front + self.size - 1) % len(self.arr)]
callsize00front12after slot 2 comes slot 0returnedempty queue: 3 slots, front at 0, size 0
front0
size0
The array has 3 empty slots. front is 0 and size is 0. There is no rear index to keep: it is always worked out from these two.
callenqueue 1size110front, rear12after slot 2 comes slot 0returnedenqueue 1: write at slot 0, size 0 → 1
callenqueue 1
front0
size1
The next free slot is front + size = 0 + 0 = 0. 1 goes there and becomes the rear; nothing else moves.
callenqueue 2size210front21rear2after slot 2 comes slot 0returnedenqueue 2: write at slot 1, size 1 → 2
callenqueue 2
front0
size2
The next free slot is front + size = 0 + 1 = 1. 2 goes there and becomes the rear; nothing else moves.
callenqueue 3size310front2132rearafter slot 2 comes slot 0returnedenqueue 3: write at slot 2, size 2 → 3
callenqueue 3
front0
size3
The next free slot is front + size = 0 + 2 = 2. 3 goes there and becomes the rear; nothing else moves.
callisFullsize310front2132rearafter slot 2 comes slot 0returnedtrueisFull: size is 3 of 3 → true
callisFull
front0
size3
size equals the array length, so every slot is in use: true. Here front and rear sit next to each other on the ring.
callenqueue 4size310front2132rearafter slot 2 comes slot 0returnedtrueenqueue 4: size is 3 → full, ignore
callenqueue 4
front0
size3
All 3 slots hold elements. The next free slot would be the front itself, so writing there would destroy the oldest element; enqueue returns without changing anything.
calldequeuesize21021front32rearafter slot 2 comes slot 0returnedtruedequeue: 1 leaves, front moves 0 → 1
calldequeue
front1
size2
1 was the oldest element. front moves to slot 1 and size drops to 2. The 1 stays in the array, faded, until an enqueue writes over it.
calldequeuesize1102132front, rearafter slot 2 comes slot 0returnedtruedequeue: 2 leaves, front moves 1 → 2
calldequeue
front2
size1
2 was the oldest element. front moves to slot 2 and size drops to 1. The 2 stays in the array, faded, until an enqueue writes over it.
callenqueue 4size240rear2132frontafter slot 2 comes slot 0returnedtrueenqueue 4: past the last slot → wraps to slot 0
callenqueue 4
front2
size2
The next free position is front + size = 3, one past the last index, so it wraps to slot 0, over the old 1 that a dequeue left behind. This is the slot an earlier dequeue freed.
callgetFrontsize240rear2132frontafter slot 2 comes slot 0returnedtrue3getFront: slot 2 holds 3 → return 3
callgetFront
front2
size2
The oldest element is at front = 2, so getFront returns 3.
callgetRearsize240rear2132frontafter slot 2 comes slot 0returnedtrue34getRear: slot 0 holds 4 → return 4
callgetRear
front2
size2
The rear is one before the next free slot: (2 + 2 − 1) mod 3 = 0, which holds 4.
callenqueue 5size34051rear32frontafter slot 2 comes slot 0returnedtrue34enqueue 5: past the last slot → wraps to slot 1
callenqueue 5
front2
size3
The next free position is front + size = 4, one past the last index, so it wraps to slot 1, over the old 2 that a dequeue left behind. This is the slot an earlier dequeue freed.
callisFullsize34051rear32frontafter slot 2 comes slot 0returnedtrue34trueisFull: size is 3 of 3 → true
callisFull
front2
size3
size equals the array length, so every slot is in use: true. Here front and rear sit next to each other on the ring.
callgetRearsize34051rear32frontafter slot 2 comes slot 0returnedtrue34true5getRear: slot 1 holds 5 → return 5
callgetRear
front2
size3
The rear is one before the next free slot: (2 + 3 − 1) mod 3 = 1, which holds 5.
callsize34051rear32frontafter slot 2 comes slot 0returnedtrue34true5returned in order: true, 3, 4, true, 5
returned[true, 3, 4, true, 5]
No call moved an element. Enqueue and dequeue each changed one index and the size, and the values returned, in order, are true, 3, 4, true, 5.
05

Common pitfalls

Letting the rear index run off the end

✗ Wrong
if self.rear == len(self.arr):
    return
self.arr[self.rear] = x
self.rear += 1
✓ Right
if self.isFull():
    return
rear = (self.front + self.size) % len(self.arr)
self.arr[rear] = x
self.size += 1

Without 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

✗ Wrong
def isEmpty(self):
    return self.front == self.rear
✓ Right
def isEmpty(self):
    return self.size == 0

With 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

✗ Wrong
return self.arr[(self.front + self.size) % len(self.arr)]
✓ Right
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.

06

Complexity

Time
O(1)
Space
O(n)
Every method does one or two comparisons and at most one array access and one modulo, however many elements are stored. The array of n slots is allocated once.
07

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.