881419. Operations on Queue

Basic

Operations on Queue

Slug: operations-on-queue--114617 Difficulty: Basic Id: 881419 Topic Tags: Queue, Data Structures Company Tags: Amazon

Summary

This problem is about implementing various queue operations such as enqueue, dequeue, and display. The key concepts involved are basic queue operations and data structures.

Detailed Explanation

The goal of this problem is to create a class Queue that implements the following methods:

  • enqueue(int item): adds an element at the end of the queue.
  • dequeue(): removes the element from the front of the queue.
  • display(): prints the elements in the queue.

Here's a step-by-step breakdown of the solution:

  1. Create a class Queue with a fixed-size array to store the elements.
  2. Initialize an empty queue by setting its size to 0 and its front index to -1.
  3. The enqueue(int item) method adds an element at the end of the queue:
    • If the queue is not full, add the element to the end of the array and increment the rear index.
    • If the queue is full, print a message indicating that the queue is full and return.
  4. The dequeue() method removes the element from the front of the queue:
    • If the queue is not empty, remove the element at the front of the array and decrement the front index.
    • If the queue is empty, print a message indicating that the queue is empty and return.
  5. The display() method prints the elements in the queue:
    • Iterate through the array from the front to the rear index and print each element.

Time complexity analysis:

  • Enqueue operation: O(1) if the queue is not full, O(n) if the queue is full (where n is the size of the queue).
  • Dequeue operation: O(1) if the queue is not empty, O(n) if the queue is empty.
  • Display operation: O(n), where n is the number of elements in the queue.

Space complexity analysis:

  • The space complexity is O(n), where n is the maximum size of the queue.

Optimized Solutions

Java

View on GeeksforGeeks
public class Queue {
    private int[] array;
    private int front, rear;

    public Queue(int size) {
        array = new int[size];
        front = rear = 0;
    }

    public void enqueue(int item) {
        if (rear < array.length - 1) {
            array[rear++] = item;
        } else {
            System.out.println("Queue is full");
        }
    }

    public int dequeue() {
        if (front != rear) {
            return array[front++];
        } else {
            System.out.println("Queue is empty");
            return -1;
        }
    }

    public void display() {
        for (int i = front; i < rear; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.