Implement a Circular queue

Pattern: Implementation

easy

A circular queue reuses the slots freed at the front by wrapping indexes with mod capacity. Keep head and count: the front is data[head], the rear is data[(head + count - 1) mod capacity], and nothing ever shifts.

The problem

Build CircularQueue(capacity) with enqueue(x) returning true, or false when full, dequeue() returning the front or -1 when empty, front() and rear() (each -1 when empty), isEmpty() and isFull().

LeetCode's Design Circular Queue asks the same with Front and Rear names; the linked GFG page explains the same ring.

Think first

  • What happens to slot 0 after the first dequeue in a plain array queue?
  • How can the back of the queue reach slot 0 again?
  • Which formula gives the rear index?

Hints

    Brute force, and why it fails

    A plain array queue with front and rear indexes that only grow eventually reports full while the front slots are empty.

    The key insight

    Treat the array as a circle. The queue is the count slots starting at head, wrapping past the end.

    Dry run

    10head
    21 
    32 
    count3

    Capacity 3. enqueue 1, 2, 3 fill slots 0, 1, 2.

    Step 1 of 4

    The plan

    enqueue(x): if count == capacity: return false
                data[(head + count) mod capacity] = x; count += 1; return true
    dequeue():  if count == 0: return -1
                x = data[head]; head = (head + 1) mod capacity; count -= 1; return x
    front():    return -1 if count == 0 else data[head]
    rear():     return -1 if count == 0 else data[(head + count - 1) mod capacity]
    isEmpty():  count == 0;  isFull(): count == capacity
    

    Complexity

    Time
    O(1) per operation
    Space
    O(capacity)

    One slot per operation.

    Edge cases

    • Rear right after a wrap, as in the dry run.
    • Empty queue: front and rear are -1.
    • Full after wrapping: isFull() must still be true.
    I've built my logic, show the code

    Java

    class CircularQueue {
        private final int[] data;
        private int head = 0, count = 0;            // the front is data[head]; the rear is count - 1 places later, wrapping
    
        public CircularQueue(int capacity) {
            data = new int[capacity];
        }
    
        public boolean enqueue(int x) {
            if (count == data.length) return false; // full
            data[(head + count) % data.length] = x; // the slot after the rear, wrapping to the start
            count++;
            return true;
        }
    
        public int dequeue() {
            if (count == 0) return -1;              // empty
            int x = data[head];
            head = (head + 1) % data.length;        // the front moves one slot, wrapping
            count--;
            return x;
        }
    
        public int front() {
            return count == 0 ? -1 : data[head];
        }
    
        public int rear() {
            return count == 0 ? -1 : data[(head + count - 1) % data.length];
        }
    
        public boolean isEmpty() {
            return count == 0;
        }
    
        public boolean isFull() {
            return count == data.length;
        }
    }

    C++

    class CircularQueue {
    public:
        vector<int> data;
        int head = 0, count = 0;                    // the front is data[head]; the rear is count - 1 places later, wrapping
    
        CircularQueue(int capacity) : data(capacity) {}
    
        bool enqueue(int x) {
            int cap = static_cast<int>(data.size());
            if (count == cap) return false;         // full
            data[(head + count) % cap] = x;         // the slot after the rear, wrapping to the start
            count++;
            return true;
        }
    
        int dequeue() {
            if (count == 0) return -1;              // empty
            int x = data[head];
            head = (head + 1) % static_cast<int>(data.size());   // the front moves one slot, wrapping
            count--;
            return x;
        }
    
        int front() {
            return count == 0 ? -1 : data[head];
        }
    
        int rear() {
            return count == 0 ? -1 : data[(head + count - 1) % static_cast<int>(data.size())];
        }
    
        bool isEmpty() {
            return count == 0;
        }
    
        bool isFull() {
            return count == static_cast<int>(data.size());
        }
    };

    Python

    class CircularQueue:
        def __init__(self, capacity: int):
            self.data = [0] * capacity
            self.head = 0                           # the front is data[head]
            self.count = 0                          # the rear is count - 1 places later, wrapping
    
        def enqueue(self, x: int) -> bool:
            if self.count == len(self.data):
                return False                        # full
            self.data[(self.head + self.count) % len(self.data)] = x   # the slot after the rear, wrapping
            self.count += 1
            return True
    
        def dequeue(self) -> int:
            if self.count == 0:
                return -1                           # empty
            x = self.data[self.head]
            self.head = (self.head + 1) % len(self.data)   # the front moves one slot, wrapping
            self.count -= 1
            return x
    
        def front(self) -> int:
            return -1 if self.count == 0 else self.data[self.head]
    
        def rear(self) -> int:
            return -1 if self.count == 0 else self.data[(self.head + self.count - 1) % len(self.data)]
    
        def isEmpty(self) -> bool:
            return self.count == 0
    
        def isFull(self) -> bool:
            return self.count == len(self.data)

    Common mistakes

    • Computing the rear as head + count - 1 without the modulo.
    • Keeping only front and rear and mixing up full with empty.

    Similar problems