Tutorialspoint
Problem
Solution
Submissions

Implement a Queue Using an Array.

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a C# program to implement a queue data structure using an array. A queue is a linear data structure that follows the First In First Out (FIFO) principle.

Example 1
  • Input:
    • Enqueue(10)
    • Enqueue(20)
    • Enqueue(30)
    • Dequeue()
    • Peek()
    • IsEmpty()
  • Output:
    • 10
    • 20
    • False
  • Explanation:
    • Step 1: Enqueue 10, 20, and 30 to get queue [10, 20, 30].
    • Step 2: Dequeue() removes and returns the front element 10.
    • Step 3: Peek() returns the current front element 20 without removing it.
    • Step 4: IsEmpty() returns false as the queue still has elements.
Example 2
  • Input:
    • Enqueue(5)
    • Dequeue()
    • Dequeue()
    • IsEmpty()
  • Output:
    • 5
    • Queue Underflow
    • True
  • Explanation:
    • Step 1: Enqueue 5 to get queue [5].
    • Step 2: First Dequeue() removes and returns 5.
    • Step 3: Second Dequeue() tries to remove from an empty queue, resulting in "Queue Underflow".
    • Step 4: IsEmpty() returns true as the queue is now empty.
Constraints
  • The capacity of the queue is fixed and determined at initialization
  • 0 ≤ Number of operations ≤ 1000
  • 0 ≤ Values enqueued to the queue ≤ 10^4
  • Time Complexity for all operations: O(1)
  • Space Complexity: O(n) where n is the queue capacity
ArraysQueueDeloittePhillips
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 an array to store elements and variables to track the front and rear indices.
  • Implement boundary checks to avoid queue overflow and underflow.
  • Initialize the front and rear indices to -1 to indicate an empty queue.
  • Handle the case when the queue becomes empty after a dequeue operation.
  • Consider implementing a circular queue to utilize the array space efficiently.

Steps to solve by this approach:

 Step 1: Create a class with an array, front and rear index variables, and a capacity variable.
 Step 2: Initialize both front and rear indices to -1 to represent an empty queue.
 Step 3: Implement Enqueue by incrementing the rear index and adding the value if the queue is not full.
 Step 4: Implement Dequeue by returning the front value and incrementing the front index if the queue is not empty.
 Step 5: Implement special case handling for when the queue becomes empty after a dequeue operation.

Submitted Code :