Skip to content

Latest commit

 

History

History
68 lines (46 loc) · 1.08 KB

File metadata and controls

68 lines (46 loc) · 1.08 KB

Design Circular Queue

Problem Link

https://leetcode.com/problems/design-circular-queue/


Pattern

  • Queue
  • Design

Approach

Use an array with front, rear, and size to implement a circular queue.


Time Complexity

O(1) per operation

Space Complexity

O(k)


Java Solution

class MyCircularQueue {
    private int[] arr;
    private int front = 0, size = 0;

    public MyCircularQueue(int k) {
        arr = new int[k];
    }

    public boolean enQueue(int value) {
        if (isFull()) return false;
        arr[(front + size) % arr.length] = value;
        size++;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) return false;
        front = (front + 1) % arr.length;
        size--;
        return true;
    }

    public int Front() {
        return isEmpty() ? -1 : arr[front];
    }

    public int Rear() {
        return isEmpty() ? -1 : arr[(front + size - 1 + arr.length) % arr.length];
    }

    public boolean isEmpty() { return size == 0; }
    public boolean isFull() { return size == arr.length; }
}