Queue

A linear data structure that follows the First-In, First-Out (FIFO) principle, where insertion happens at the rear and deletion happens from the front.

Types of Queues

1️⃣ Linear Queue

A queue where elements are added at the rear and removed from the front, following FIFO.

Example: Waiting line.

10
Front
20

2️⃣ Circular Queue

A queue where the last position connects back to the first, reusing empty space.

Use Case: Used to avoid wasted memory.

10
20
30
Front
Rear

3️⃣ Priority Queue

A queue where elements are served based on priority, not arrival order.

Example: Emergency patients in a hospital.

P2
P3

4️⃣ Double-Ended Queue

A queue where insertion and deletion can happen at both front and rear.

Key Feature: Flexible structure.

20
30

FIFO Principle (First-In, First-Out)

Dequeue (Remove from front)
Enqueue (Add to back)

FIFO means the first element added to a collection is the first one to be removed.

Enqueue

10
20

Enqueue adds an element to the back (or end) of the queue, with O(1) time complexity.

Dequeue

10
20
30

Dequeue removes the front element from the queue, with O(1) time complexity.

Peek

10
20
30
40

Peek returns the front element without removing it, with O(1) time complexity.

Search

10
20
30
40

Search must check each element from the front, resulting in O(n) time complexity.

Time Complexity

OperationTime ComplexityNotes
EnqueueO(1)Add element to the rear
DequeueO(1)Remove element from the front
PeekO(1)View front element without removal
SearchO(n)Requires scanning from the front
TraversalO(n)Requires visiting all elements

When to Use Queues

  • Processing tasks in the order they were received, like a printer queue.
  • Implementing Breadth-First Search (BFS) in graph and tree traversal algorithms.
  • Managing requests in a web server or tasks in an operating system scheduler.
  • Buffering data in streams (e.g., video streaming) where data is processed in the order it arrives.