DSA Queue

Queue Data Structure

Key Takeaways: A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. The very first element added to the queue will be the very first element removed from it.

In the previous tutorial, we learned about Stacks (LIFO). Now, let's look at its sibling data structure: the Queue.

A Queue is exactly like waiting in line in real life. The rules are simple and fair!


1. What is a Queue?

A Queue operates on the First In, First Out (FIFO) principle.

Think of a line of people waiting to buy movie tickets. The person who arrives first gets their ticket first. When a new person arrives, they must join the back of the line.

Real-Life Examples of Queues:

A Queue: Elements enter at the Rear and leave from the Front. Try it out!


2. Core Queue Operations

Just like a Stack, a proper Queue restricts how you can access the data.

Here are the standard terms used in DSA for Queue operations:

  1. Enqueue: Add a new element to the Rear (Back) of the queue.
  2. Dequeue: Remove and return the element at the Front of the queue.
  3. Peek (or Front): Look at the front element without removing it.
  4. isEmpty: Check if the queue has no elements.

3. Time Complexity of a Queue

A well-implemented Queue is incredibly fast.

Important Note: If you use a standard Array/List to build a Queue, removing the front item forces you to shift all the other items over, which drops the Dequeue speed to O(n). To get O(1) speed, Queues are usually built using Linked Lists under the hood!


4. Queue Code Example (Python)

In Python, standard lists are very slow for queues because inserting or deleting at index 0 requires shifting all the other elements.

Instead, Python developers use collections.deque (Double-Ended Queue) which is optimized for fast O(1) enqueues and dequeues!

Using Python collections.deque

from collections import deque
# Create an empty queue
queue = deque()
# 1. ENQUEUE (Add to the back)
print("Enqueueing elements...")
queue.append("A")
queue.append("B")
queue.append("C")
print("Current Queue:", list(queue))
# 2. PEEK at the front element
# Index 0 is always the front of the queue
front_element = queue[0]
print("Front element is:", front_element)
# 3. DEQUEUE (Remove from the front)
print("Dequeueing element...")
removed_item = queue.popleft()

print("Removed:", removed_item) print("Queue after Dequeue:", list(queue))


Exercise 1 of 2

?

What core principle does a Queue follow?

Exercise 2 of 2

?

What is the correct term for removing an item from the front of a Queue?