Course contentsShow
← Computer Science
Lesson 387 of 2,8729. Stacks and QueuesFree lesson

Circular Queues

Implementing queues with wraparound using modular arithmetic to efficiently reuse array space.

Circular Queues

You'll learn how circular queues use wraparound logic to reuse array space efficiently.

What's the Problem?

In a simple array-based queue, you use two indices: front (where you dequeue) and rear (where you enqueue). As you add and remove elements, both indices move forward. Eventually, rear reaches the end of the array—but the spaces at the beginning might be empty! This wastes memory.

The Circular Solution

A circular queue treats the array as if it wraps around—like a clock face. When an index reaches the last position, it loops back to position 0. This lets you reuse freed-up space at the front of the array.

How Wraparound Works

The magic is modular arithmetic using the % operator:

nextIndex = (currentIndex + 1) % arraySize

If currentIndex is at position arraySize - 1 (the last slot), adding 1 gives arraySize, and arraySize % arraySize = 0—wrapping back to the start!

Example:

  • Array size = 5
  • rear is at index 4 (last position)
  • Next enqueue: rear = (4 + 1) % 5 = 0 (wraps to front)

Detecting Full vs Empty

Both conditions have front == rear, so you typically:

  • Keep a count variable, or
  • Leave one slot empty (queue full when (rear + 1) % size == front)

This ensures you can distinguish between an empty queue and a completely full one.

Key Takeaway:
Circular queues use modular arithmetic to wrap array indices, efficiently reusing space and avoiding the "false full" problem of linear array queues.