🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Queue Data Structure — FIFO, Enqueue, Dequeue — Complete Beginner Guide

Data Structures FoundationsQueue Data Structure — FIFO, Enqueue, Dequeue🟢 Free Lesson

Queue Data Structure — FIFO, Enqueue, Dequeue — Complete Beginner Guide

Learning Objectives

  • Define first-in, first-out queue behavior
  • Implement enqueue and dequeue correctly
  • Explain front and rear endpoints
  • Compare list-based and deque-based queues
  • Connect queues to printing, BFS, and task scheduling

What Is a Queue?

A queue is a linear structure with two open ends. You add items at the rear and remove items from the front. The first item that arrives is the first item that leaves. That rule is first-in, first-out, or FIFO.

Think of a line at a coffee shop. New people join at the back, and the person at the front orders next.

python
from collections import deque


class Queue:
    def __init__(self):
        self.items = deque()

    def enqueue(self, value):
        self.items.append(value)

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from empty queue")
        return self.items.popleft()

    def front(self):
        if self.is_empty():
            raise IndexError("front on empty queue")
        return self.items[0]

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)


q = Queue()
q.enqueue("job1")
q.enqueue("job2")
q.enqueue("job3")
print(q.front())   # job1
print(q.dequeue()) # job1
print(q.dequeue()) # job2

Core Operations

OperationDescriptionTime
enqueueAdd item at rearO(1)
dequeueRemove item from frontO(1)
front or peekRead front itemO(1)
is emptyCheck sizeO(1)
search by valueMay scan all itemsO(n)

Why Not Use a Plain List?

Using pop at index zero of a Python list is O(n) because every remaining item shifts left. Using deque keeps both ends at O(1).

Backendenqueuedequeue frontMemory
Python list append plus pop zeroO(1) appendO(n) pop frontCompact
collections.dequeO(1)O(1)Slightly larger
Fixed circular bufferO(1)O(1)Predictable
python
# Efficient queue in practice
from collections import deque

line = deque()
line.append("alice")    # enqueue
line.append("bob")
first = line.popleft()  # dequeue
print(first, list(line))

FIFO Walkthrough

Follow a small sequence to lock in the order.

  1. enqueue A, so the queue holds A
  2. enqueue B, so the queue holds A then B
  3. enqueue C, so the queue holds A then B then C
  4. dequeue returns A
  5. dequeue returns B
  6. dequeue returns C

The exit order matches the entry order even though arrivals were staggered.

Real-World Applications

  • Printers process documents in arrival order
  • Message brokers buffer events before workers consume them
  • CPU and disk schedulers queue processes or requests
  • Breadth-first search uses a queue to explore level by level
  • Customer support systems serve tickets FIFO for fairness
  • Keyboard buffers hold keystrokes until processed

Simple Task Processor

python
from collections import deque

def process_tasks(tasks):
    queue = deque(tasks)
    done = []
    while queue:
        task = queue.popleft()
        done.append(task.upper())
    return done


print(process_tasks(["email", "upload", "sync"]))

Queue Variants

Plain FIFO queues spawn several cousins you will meet later:

  • Circular queues reuse array slots in a ring
  • Deques allow both front and rear operations
  • Priority queues always release the highest priority item
  • Double-ended queues power sliding window problems

Queue Simulation and Variants Drill

Simulate a short queue script the same way you would for a stack. Start empty. Enqueue one, enqueue two, enqueue three. The front is one. Dequeue returns one and leaves two then three. Enqueue four appends at the rear, giving two, three, four. Two more dequeues leave only four.

StepOperationFront to RearOutput
1enqueue 11none
2enqueue 21 2none
3enqueue 31 2 3none
4dequeue2 31
5enqueue 42 3 4none
6dequeue3 42
7dequeue43

After the simulation, try the same script with a stack and compare exit order. That contrast cements FIFO versus LIFO. Then swap in a circular buffer mentally and confirm that freed front slots can be reused at the rear without breaking order.

Key Takeaways

💡

  • Queues follow first-in, first-out order with enqueue at rear and dequeue at front
  • collections.deque gives O(1) enqueue and dequeue
  • Popping index zero of a plain list costs O(n) because of shifts
  • BFS, printers, and task schedulers are classic queue workloads
  • Circular queues and deques are common optimized variants

Practice Questions

  1. Enqueue 1, 2, 3 then dequeue twice. Which value remains, and why?
  2. Explain why list pop at the front is O(n) while deque popleft is O(1).
  3. Describe a scenario where a priority queue would beat a plain FIFO queue.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement