Tutorialspoint
Problem
Solution
Submissions

Queue using Array

Certification: Basic Level Accuracy: 100% Submissions: 6 Points: 8

Write a Java program to implement a queue using an array. The queue should support enqueue, dequeue, peek, isEmpty, and isFull operations.

Example 1
  • Input:
    enqueue(10)
    enqueue(20)
    enqueue(30)
    dequeue()
    peek()
  • Output:
    10 dequeued from the queue
    Front element is: 20
  • Explanation:
    • Queue is FIFO. 10 dequeued, 20 is now at front
Example 2
  • Input:
    enqueue(10)
    isEmpty()
    enqueue(20)
    enqueue(30)
    isFull()
    dequeue()
    dequeue()
    dequeue()
    isEmpty()
  • Output:
    Queue is not empty
    Queue is not full
    10 dequeued
    20 dequeued
    30 dequeued
    Queue is empty
Constraints
  • Fixed capacity set during initialization
  • Time Complexity: O(1)
  • Space Complexity: O(n)
  • Must handle overflow and underflow
ArraysQueueTutorialspointTCS (Tata Consultancy Services)
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a circular array to efficiently utilize space.
  • Keep track of both front and rear indices.
  • For enqueue, increment rear and add the element.
  • For dequeue, remove the front element and increment front.
  • Use modulo arithmetic to handle wraparound in the circular array.

Steps to solve by this approach:

 Step 1: Create a class with an array, variables to track front and rear indices, size, and capacity.
 Step 2: Initialize front and size to 0, and rear to capacity-1 in the constructor.
 Step 3: Implement the enqueue method by updating rear using modulo arithmetic and adding the element.
 Step 4: Implement the dequeue method by returning the element at front and updating front using modulo arithmetic.
 Step 5: Implement the peek method to return the element at front without modifying any indices.
 Step 6: Implement isEmpty method to check if size is 0.
 Step 7: Implement isFull method to check if size equals capacity.

Submitted Code :