Queue

DSA · Stacks and Queues

Theory

A queue is a First-In-First-Out (FIFO) collection: items are added at the back (enqueue) and removed from the front (dequeue), like a line at a ticket counter. Both operations should be O(1). Using list.pop(0) is O(n) because every element shifts, so Python code uses collections.deque, which is a double-ended queue with O(1) operations at both ends.

Why we use it

Queues process work in arrival order, which keeps systems fair and predictable.

When to use it

Use queues for task scheduling, printer jobs, message processing, rate limiting, and breadth-first search.

How it works

  1. Empty queue
  2. Enqueue? Yes: Add item at the rear. No: Dequeue: remove from the front.
  3. Queue empty when dequeuing? Yes: Underflow. No: Return the front item.
  4. FIFO: first in, first out

Syntax

from collections import deque
q = deque()
q.append(x)    # enqueue  O(1)
q.popleft()    # dequeue  O(1)
q[0]           # front

Example

from collections import deque

orders = deque()
for o in ["Order#101", "Order#102", "Order#103"]:
    orders.append(o)
    print("Received", o)

while orders:
    print("Preparing", orders.popleft(), "| waiting:", list(orders))

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic