VOOZH about

URL: https://www.geeksforgeeks.org/dsa/fill-and-empty-a-queue/

⇱ Fill and Empty a Queue - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Fill and Empty a Queue

Last Updated : 23 Jul, 2025

Given an empty queue and an array of elements, we need to perform the following two operations.

1. Filling a Queue

Filling a queue refers to the process of adding array elements to it. In a queue, elements are added to the rear or back of the queue.

  • Insert Elements: You begin by inserting elements into the queue, typically one by one using an operation such as enqueue or push (depending on the language or context).
  • Order: Each element is added at the back of the queue, and the order in which they are added is maintained. The first element inserted will be at the front of the queue when it is dequeued (removed).

2. Emptying a Queue

Emptying a queue means removing elements from it. In a queue, elements are removed from the front of the queue, adhering to the FIFO rule.

  • Remove Elements: The elements are removed from the front of the queue using an operation like dequeue or pop.
  • Order of Removal: The first element that was added to the queue is the first to be removed. This continues until the queue is empty.

Examples:

Input: arr[] = [1, 2, 3, 4, 5]
Output: 1 2 3 4 5
Explanation: Enqueue the elements of the array into a queue in the same order, then dequeue and print the elements, resulting in the same order as the input: 1 2 3 4 5.

Input: arr[] = [1, 6, 43, 1, 2, 0, 5]
Output: 1 6 43 1 2 0 5
Explanation: Enqueue the elements of the array into a queue in the same order, then dequeue and print the elements, resulting in the same order as the input: 1 6 43 1 2 0 5.

The approach uses a queue, which follows the First-In-First-Out (FIFO) principle. Elements are added to the back and removed from the front in the same order they were added. The first element inserted is the first one to be removed, ensuring they are processed in the order they arrive.


Output
1 2 3 4 5 

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags: