← Back

🎫 Queue Pattern

First In, First Out (FIFO)

👶Explain Like I'm 5

Imagine standing in line at a ticket counter...

The person who came FIRST gets served first and leaves from the FRONT. New people join at the BACK of the line. Everyone waits their turn - no cutting in line!

Why is this useful? Queues help us handle things fairly in order. Like printing documents, processing tasks, or managing requests!

Real-world use cases:

  • Printer queue (print jobs)
  • Customer service lines
  • Breadth-First Search (BFS) algorithm
  • Task scheduling in operating systems
  • Message queues in distributed systems

Interactive Queue Visualization

🎯 Queue: First In, First Out (FIFO)

FRONT ➡️
⬅️ REAR

Queue is empty 📭

Size
0
Front Element
N/A
Is Empty?
Yes

Queue Operations

➡️ENQUEUE(x)

Add element to the REAR of queue. O(1) time complexity.

⬅️DEQUEUE()

Remove and return FRONT element. O(1) time complexity.

👀PEEK() / FRONT()

View FRONT element without removing it. O(1) time complexity.

isEmpty()

Check if queue is empty. O(1) time complexity.

⚖️Stack vs Queue

📚 Stack (LIFO)

Last In, First Out - like plates

Add & Remove from SAME end (top)

🎫 Queue (FIFO)

First In, First Out - like a line

Add at REAR, Remove from FRONT

🎯When to Use Queue?

Keywords: “order”, “first come first serve”, “level by level”, “BFS”
Need to: Process items in the order they arrived
Problems: BFS traversal, level-order tree traversal, task scheduling
💡
Pro Tip: If you need “fair ordering” or “first added”, think Queue!