DSA Tutorial menu

DSA Stacks and Queues

Stacks and queues are simple lists with strict rules about where items go in and come out.

What is a Stack?

A stack is like a pile of plates at a wedding buffet. You put a new plate on top, and you also take a plate from the top. The last plate placed is the first one taken.

This rule is called LIFO: Last In, First Out.

OperationMeaningBig O
pushPut an item on topO(1)
popRemove the top itemO(1)
peekLook at the top item without removing itO(1)
is emptyCheck if the stack has no itemsO(1)

A Stack in Python

A Python list works well as a stack. append pushes onto the end (the top), and pop removes from the end.

Example

python
stack = []
stack.append("Page 1")
stack.append("Page 2")
stack.append("Page 3")
print(stack[-1])

print(stack.pop())
print(stack.pop())
print(stack)
Output
Page 3
Page 3
Page 2
['Page 1']

This is how the Back button of a browser works: each new page is pushed, and Back pops the latest one.

Stack Example: Checking Brackets

Code editors use a stack to check that every bracket is closed in the right order.

Example

python
def balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in ")]}":
            if not stack or stack.pop() != pairs[ch]:
                return False
    return len(stack) == 0

print(balanced("(a + b) * [c - d]"))
print(balanced("{[(])}"))
print(balanced("((x)"))
Output
True
False
False

Each opening bracket is pushed. Each closing bracket must match the bracket on top of the stack.

What is a Queue?

A queue is like a line at a bank counter. People join at the back and are served from the front. The first person to arrive is the first to be served.

This rule is called FIFO: First In, First Out.

OperationMeaningBig O
enqueueAdd an item at the backO(1)
dequeueRemove the item at the frontO(1)
frontLook at the first itemO(1)

A Queue in Python

Do not use list.pop(0) for a queue: it is O(n) because every item shifts. Use collections.deque, which adds and removes at both ends in O(1).

Example

python
from collections import deque

counter = deque()
counter.append("Ali")
counter.append("Sara")
counter.append("Hamza")

print("Serving:", counter.popleft())
print("Serving:", counter.popleft())
counter.append("Ayesha")
print("Waiting:", list(counter))
Output
Serving: Ali
Serving: Sara
Waiting: ['Hamza', 'Ayesha']

Queues are everywhere: printer jobs, messages waiting to be sent, and orders in a food delivery app are all handled in the order they arrived.

Stack vs Queue

StackQueue
RuleLIFOFIFO
Addpush (top)enqueue (back)
Removepop (top)dequeue (front)
Real usesUndo, browser back, function callsPrinting, task scheduling, BFS in graphs

A priority queue is a special queue where the most important item leaves first, for example patients in an emergency room. Python's heapq module provides one.

Exercise

Exercise

You push 1, then 2, then 3 onto an empty stack, then pop once. Which item is removed?

Learn DSA with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp