algoadvance

Leetcode 622. Design Circular Queue

Problem Statement

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called “Ring Buffer”.

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

Your implementation should support following operations:

Clarifying Questions

  1. Can the elements in the queue be non-integer values?
    • For the purpose of this problem, we will assume the queue holds integer values.
  2. Do we need to handle concurrency?
    • No, assume all operations are performed sequentially.
  3. Should we perform input validation for the methods?
    • Assume valid inputs (e.g., enQueue will only receive integer values).

Strategy

  1. Use an array to store the elements of the queue.
  2. Maintain two pointers, front and rear, to indicate the start and end of the queue.
  3. Keep a count of the current number of elements in the queue to determine when it’s full or empty.

Methods:

Time Complexity

Let’s implement this:

Code

public class MyCircularQueue {
    private int[] queue;
    private int front;
    private int rear;
    private int count;
    private int capacity;

    public MyCircularQueue(int k) {
        this.capacity = k;
        this.queue = new int[capacity];
        this.front = 0;
        this.rear = 0;
        this.count = 0;
    }
    
    public boolean enQueue(int value) {
        if (isFull()) return false;
        queue[rear] = value;
        rear = (rear + 1) % capacity;
        count++;
        return true;
    }
    
    public boolean deQueue() {
        if (isEmpty()) return false;
        front = (front + 1) % capacity;
        count--;
        return true;
    }
    
    public int Front() {
        if (isEmpty()) return -1;
        return queue[front];
    }
    
    public int Rear() {
        if (isEmpty()) return -1;
        return queue[(rear - 1 + capacity) % capacity];
    }
    
    public boolean isEmpty() {
        return count == 0;
    }
    
    public boolean isFull() {
        return count == capacity;
    }
}

This code covers all the required operations for the circular queue with time complexities as mentioned.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI