DSA in 30 Days, Episode 4: Stacks, Postfix Evaluation and Circular Queues

Home / DSA series / Episode 4

Last updated: October 12, 2026

A stack removes the last item added: last in, first out (LIFO). A queue removes the first item added: first in, first out (FIFO). The storage can look similar, but the rule for removal changes the answer.

This lesson follows stack operations, postfix expression evaluation, bracket matching and circular queues. The examples and answers were checked by a Python program. The circular queue was also checked against Python's deque through 5,000 seeded random enqueue/dequeue attempts, including full and empty cases. This is a general BTech CSE guide, not an official college syllabus.

Video for this lesson: the link will be added when the matching video is available. You can study the complete written lesson below now.

Previous: Episode 3: merge, quick, counting and radix sort. Next: Episode 5: linked lists. Full series index.

What, why, where used, how

  • What: a stack and a queue are rules for adding and removing items. They are abstract data types; an array or linked list can implement them.
  • Why: many problems need a specific order. The most recent unfinished task needs a stack; the oldest waiting task needs a queue.
  • Where used: stacks help evaluate expressions, match brackets and manage nested function calls. Queues help process requests in arrival order and visit graph nodes in breadth-first search.
  • How: stack push adds at the top, pop removes from the top, and peek reads the top without removal. Queue enqueue adds at the rear and dequeue removes from the front.

Difference: stack, queue, deque and priority queue

The removal rule is the first thing to identify in an exam. A deque permits both ends; using only one pair of operations can make it act as a stack or a queue. A priority queue is not a synonym for FIFO.

StructureAdd/remove ruleAfter adding 10, 20, 30Useful when
StackPush and pop at the same endFirst pop: 30Nested unfinished work
FIFO queueEnqueue at rear, dequeue at frontFirst dequeue: 10Arrival order matters
DequeInsert/remove at either endDepends on the chosen endBoth ends are needed
Priority queueRemove by priority, not arrival aloneCannot decide without prioritiesUrgent work should go first
Stack: bottom [10] [20] [30] <- top: push/pop here
Queue: front  [10] [20] [30]  rear
                |           ^
             dequeue     enqueue

Stack operations: watch the top

Picture a stack of plates. You add and remove at the same end. In our tables, the leftmost value is the bottom and the rightmost value is the top. Start with an empty stack. Push 10, push 20, pop, push 30, peek, pop, pop.

OperationStack: bottom to topReturnedTop index
push 10[10]-0
push 20[10, 20]-1
pop[10]200
push 30[10, 30]-1
peek[10, 30]301
pop[10]300
pop[]10-1

The returned pop values are 20, 30 and 10. Peek returns 30 without changing the stack. For a fixed array using zero-based indexes, the top index starts at -1. After each successful push it increases by one, and after each successful pop it decreases by one. A top index of -1 means empty, not a valid item position.

Underflow means trying to remove or read an item when there is none. A fixed-capacity stack can also have overflow when a push is attempted while full. A dynamic Python list grows when needed, so it does not use that fixed-capacity full test, though memory is still finite.

stack = []
stack.append(10)       # push
stack.append(20)
print(stack[-1])       # peek: 20
print(stack.pop())     # pop: 20
print(stack)           # [10]
# Check `if stack:` before peek or pop on uncertain input.

Postfix: operators come after their operands

Infix writes the operator between values: (12 - 3) * 2 + 6. Postfix writes the operator after the values it uses: 12 3 - 2 * 6 +. Spaces separate tokens, so 12 is one number, not the separate digits 1 and 2. The order already says which calculation happens next; no parentheses are needed.

Read tokens from left to right. Push a number. For an operator, pop the right operand first, then the left operand. Calculate left operator right and push the result. At the end, exactly one value must remain.

TokenStack: bottom to top
1212
312, 3
-9
29, 2
*18
618, 6
+24
Result: 24. The subtraction produces 9, multiplication produces 18, and addition produces 24. There are seven tokens and three operators. This is a token trace, not a runtime benchmark.

The operand-order trap: for 20 5 / 3 -, pop 5 then 20 and calculate 20 / 5 = 4. Next calculate 4 - 3 = 1. Swapping the popped values gives a different answer. Addition can hide this bug because a + b equals b + a; subtraction and division reveal it.

Use a stack for unfinished values, not for operators during evaluation. Infix-to-postfix conversion is a different task: it uses an operator stack and precedence rules. For example, A + B * C becomes A B C * +, while (A + B) * C becomes A B + C *.

Runnable postfix evaluator

This original Python code supports space-separated numbers and the binary operators +, -, * and /. Fraction keeps rational results exact. It does not support unary operators as separate tokens, variables or exponentiation. A signed number such as -3 is accepted as one numeric token. Division by zero is rejected by Python.

from fractions import Fraction

def evaluate_postfix(expression):
    stack = []
    for token in expression.split():
        if token not in ("+", "-", "*", "/"):
            stack.append(Fraction(token))
            continue
        if len(stack) < 2:
            raise ValueError("Not enough operands")
        right = stack.pop()
        left = stack.pop()
        if token == "+": result = left + right
        elif token == "-": result = left - right
        elif token == "*": result = left * right
        else: result = left / right
        stack.append(result)
    if len(stack) != 1:
        raise ValueError("Extra operands or empty expression")
    return stack[0]

print(evaluate_postfix("12 3 - 2 * 6 +"))  # 24
print(evaluate_postfix("20 5 / 3 -"))      # 1

With n tokens and fixed-size arithmetic, evaluation takes O(n) time and at most O(n) extra stack space. Very large Fraction numerators and denominators add arithmetic costs; the classroom O(n) model does not measure those bit-level costs.

Bracket matching: nesting matters

Counting opening and closing brackets is not enough. ([)] has matching counts but wrong nesting. Push each opening bracket. When a closing bracket appears, the top must be its matching opener. Reject a closing bracket if the stack is empty or the types differ. Accept only if the stack is empty after the last character.

{[()]} is balanced. ([)] is not balanced: when ) arrives, the top is [ rather than (. (() is not balanced because an opening bracket remains. This simple method checks brackets in a plain string. Parsing brackets inside quoted strings or comments needs extra language-aware rules.

Bracket trace: equal counts are not enough

Character in ([)]Stack beforeDecision
([]Push (
[["("]Push [
)["(", "["]Reject: top is [, not (
]Not reachedStop at the first mismatch

The stack invariant is that it holds unmatched opening brackets in nesting order. The top is the only opener that can match the next closer. An empty string is balanced. This implementation ignores non-bracket characters, so a[b] passes, but it does not understand quotes or comments.

def balanced(text):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in text:
        if char in '([{':
            stack.append(char)
        elif char in pairs:
            if not stack or stack.pop() != pairs[char]:
                return False
    return not stack

for text in ['{[()]}', '([)]', '(()', '', 'a[b]']:
    print(repr(text), balanced(text))
'{[()]}' True
'([)]' False
'(()' False
'' True
'a[b]' True

Queues: use the front, not the most recent item

Enqueue 10, 20 and 30. A queue's first dequeue returns 10, while a stack's first pop would return 30. If we enqueue 40 after removing 10, the queue's logical order is 20, 30, 40. Do not sort these values: FIFO is about arrival order, not numerical size or priority.

from collections import deque
queue = deque([10, 20, 30])
print(queue.popleft())  # 10
queue.append(40)
print(list(queue))     # [20, 30, 40]

Python list pop(0) shifts the remaining items and costs O(n). A deque supports fast operations at both ends. Stack operations at the end of a Python list have amortized O(1) cost; resizing can make an individual operation slower. The data type's rule and the implementation's cost are separate ideas.

Circular queue: reuse slots without shifting

A simple fixed array queue can leave unused slots before its front. A circular queue wraps indexes around with modulo. Our version stores front (the next item to remove) and count (the number of stored items). For capacity k, insert at (front + count) % k. After removal, set front = (front + 1) % k.

Here capacity is 4 and every slot is usable. Empty means count = 0; full means count = 4. Other textbook versions reserve one empty slot to distinguish front and rear, giving usable capacity k - 1. Do not mix their full test with this count-based version.

OperationReturnedPhysical slots 0 to 3FrontCountFIFO order
enqueue 10-[10, None, None, None]01[10]
enqueue 20-[10, 20, None, None]02[10, 20]
enqueue 30-[10, 20, 30, None]03[10, 20, 30]
dequeue10[None, 20, 30, None]12[20, 30]
enqueue 40-[None, 20, 30, 40]13[20, 30, 40]
enqueue 50-[50, 20, 30, 40]14[20, 30, 40, 50]
dequeue20[50, None, 30, 40]23[30, 40, 50]

After enqueueing 50, the physical array is [50, 20, 30, 40], but the logical FIFO order is [20, 30, 40, 50]. The oldest item is still 20 at front index 1. After the last dequeue, front is 2, count is 3, and the remaining logical order is [30, 40, 50]. Reading physical slots from index zero would give the wrong order.

class CircularQueue:
    def __init__(self, capacity):
        if capacity <= 0:
            raise ValueError("Capacity must be positive")
        self.data = [None] * capacity
        self.front = 0
        self.count = 0

    def enqueue(self, value):
        if self.count == len(self.data):
            raise OverflowError("Queue full")
        slot = (self.front + self.count) % len(self.data)
        self.data[slot] = value
        self.count += 1

    def dequeue(self):
        if self.count == 0:
            raise IndexError("Queue empty")
        value = self.data[self.front]
        self.data[self.front] = None
        self.front = (self.front + 1) % len(self.data)
        self.count -= 1
        return value

Enqueue and dequeue take O(1) time in this fixed-capacity version because they update one slot and a small number of fields, without shifting items. Storage is O(k). The count determines occupancy, so even a stored None does not mean an empty slot.

Wraparound is an index rule, not a new order

Capacity 4, after enqueue 50:
physical index:     0     1     2     3
physical value:    50    20    30    40
                         ^
                      front=1, count=4
logical read path:  1 -> 2 -> 3 -> 0
FIFO values:       20   30   40   50
next write slot: (1 + 4) % 4 = 1, but FULL: do not write

The next-write formula alone does not authorize insertion. Check count before writing, or a full queue will overwrite its oldest item. After the dequeue in the original trace, front becomes 2 and count becomes 3, so the next enqueue uses slot (2 + 3) % 4 = 1. Clearing a removed slot is useful for releasing its reference, but count, not None, determines whether data exists.

Full and empty conventions: state your version

ConventionEmptyFullUsable slots
This page: front + countcount == 0count == kk
One unused slot; rear is next writefront == rear(rear + 1) % k == frontk - 1

In the second convention, front points to the next removal slot and rear to the next insertion slot. Some books use rear for the last stored item instead, so their initial values and tests change. Copying a full test without its index definitions is unsafe. A bounded Python deque also differs from this class: append on a full deque(maxlen=k) discards an item at the opposite end; this class rejects the enqueue.

Capacity-one boundary

With capacity 1, enqueue(None) sets count to 1 and uses slot 0. Another enqueue raises OverflowError without changing state. Dequeue returns the stored None, count becomes 0, and front stays 0 because (0 + 1) % 1 = 0. A second dequeue raises IndexError. Capacity 0 or a negative capacity is rejected before any modulo operation.

Run independent boundary checks

Run the lab below after the original evaluate_postfix and CircularQueue definitions and the balanced function above. It checks exact rational results for all a, b, c from -3 through 3 with two binary operators; division-by-zero cases are tested separately. A recursive bracket grammar supplies an independent oracle for all bracket-only strings of length 0 through 6. For each queue capacity 1 through 6, it compares 5,000 seeded attempts with deque, including None and duplicate values, and checks that rejected operations preserve every field. These are correctness tests, not timing measurements.

# Run after evaluate_postfix, balanced and CircularQueue.
from collections import deque
from fractions import Fraction
from itertools import product
from random import Random

# Independent arithmetic expressions: (a op1 b) op2 c.
def arithmetic(left, right, operator):
    if operator == '+': return left + right
    if operator == '-': return left - right
    if operator == '*': return left * right
    return left / right

expressions = zero_divisions = 0
for a, b, c in product(range(-3, 4), repeat=3):
    for op1, op2 in product('+-*/', repeat=2):
        expression = f'{a} {b} {op1} {c} {op2}'
        try:
            expected = arithmetic(arithmetic(Fraction(a), Fraction(b), op1),
                                  Fraction(c), op2)
        except ZeroDivisionError:
            try:
                evaluate_postfix(expression)
            except ZeroDivisionError:
                zero_divisions += 1
            else:
                raise AssertionError('Expected division by zero')
        else:
            assert evaluate_postfix(expression) == expected
            expressions += 1
invalid = ['', '2 3', '2 +', '+', 'a', '1 2 + 3']
for expression in invalid:
    try:
        evaluate_postfix(expression)
    except ValueError:
        pass
    else:
        raise AssertionError('Accepted malformed expression')

# Independent recursive grammar oracle, not a second stack checker.
def grammar_accepts(text):
    pairs = {'(': ')', '[': ']', '{': '}'}
    def parse_sequence(index):
        while index < len(text) and text[index] in pairs:
            closing = pairs[text[index]]
            index, ok = parse_sequence(index + 1)
            if not ok or index >= len(text) or text[index] != closing:
                return index, False
            index += 1
        return index, True
    end, ok = parse_sequence(0)
    return ok and end == len(text)

brackets = 0
for length in range(7):
    for chars in product('()[]{}', repeat=length):
        text = ''.join(chars)
        assert balanced(text) == grammar_accepts(text)
        brackets += 1

attempts = full = empty = 0
for capacity in range(1, 7):
    queue = CircularQueue(capacity)
    reference = deque()
    rng = Random(400 + capacity)
    for _ in range(5000):
        before = (queue.data.copy(), queue.front, queue.count)
        if rng.randrange(2):
            value = rng.choice([None, 0, 0, 1, -1])
            if len(reference) == capacity:
                try: queue.enqueue(value)
                except OverflowError: full += 1
                else: raise AssertionError('Expected overflow')
                assert (queue.data, queue.front, queue.count) == before
            else:
                queue.enqueue(value)
                reference.append(value)
        elif not reference:
            try: queue.dequeue()
            except IndexError: empty += 1
            else: raise AssertionError('Expected underflow')
            assert (queue.data, queue.front, queue.count) == before
        else:
            assert queue.dequeue() == reference.popleft()
        logical = [queue.data[(queue.front + i) % capacity]
                   for i in range(queue.count)]
        assert logical == list(reference)
        assert 0 <= queue.front < capacity
        assert queue.count == len(reference)
        attempts += 1
for capacity in [0, -1]:
    try: CircularQueue(capacity)
    except ValueError: pass
    else: raise AssertionError('Expected capacity rejection')

print('Postfix exact results:', expressions)
print('Division-by-zero rejections:', zero_divisions)
print('Malformed-expression rejections:', len(invalid))
print('Bracket strings checked:', brackets)
print('Queue attempts across capacities 1..6:', attempts)
print('Unchanged-state full rejections:', full)
print('Unchanged-state empty rejections:', empty)

Executed output:

Postfix exact results: 5103
Division-by-zero rejections: 385
Malformed-expression rejections: 6
Bracket strings checked: 55987
Queue attempts across capacities 1..6: 30000
Unchanged-state full rejections: 4161
Unchanged-state empty rejections: 3835

Exam answers: rules and boundary cases

QuestionShort answer
Why pop right before left?The most recent operand is on top. Subtraction and division must preserve left operator right.
Does one final value prove the input is valid?No. Each operator also needs two operands, and numeric tokens must parse successfully.
Postfix evaluation or conversion?Evaluation stores values; infix conversion stores pending operators and applies precedence.
Why can ([)] fail despite equal counts?Nesting is wrong: ) meets [ on top.
Does None mean a free circular slot?No. None may be real data; count tracks occupancy.
Can front equal the next-write slot in a full queue?Yes in the count-based version. count distinguishes full from empty.
Why is enqueue O(1) here?One slot and a few fields change; capacity is fixed and no items shift.
Is list pop always O(1)?End pop is amortized O(1); pop(0) shifts items and costs O(n).

Questions this topic can ask

  • Definition: explain LIFO and FIFO using a removal example.
  • Trace: write stack contents and returned values after push, pop and peek.
  • Numerical: evaluate a postfix expression and show the stack after each token.
  • Algorithm: describe bracket matching, including empty-stack and leftover-opener checks.
  • Difference: compare ordinary and circular array queues; name your full/empty convention.
  • Complexity: explain why list pop(0) costs more than deque popleft.
  • Application: choose a stack for nested unfinished work or a queue for arrival-order processing.

Practice first, then check

  1. Evaluate 8 2 3 * +.
  2. Evaluate 9 4 - 2 *.
  3. Evaluate 10 2 / 3 +.
  4. Is ([)] balanced? Explain without just counting brackets.
  5. A count-based circular queue has capacity 4, front 3 and count 2. At which slot does the next enqueue write?
  6. Push 10 and 20, pop, push 30. What does peek return?
  7. Is 2 3 a complete postfix expression? What about 2 +?
Answers:
  1. 14: multiply 2 by 3, then add 8.
  2. 10: subtract 4 from 9, then multiply by 2.
  3. 8: divide 10 by 2, then add 3.
  4. No. The closing ) encounters [ at the top.
  5. Slot 1: (3 + 2) % 4 = 1.
  6. 30, without removing it.
  7. Neither is complete. The first leaves two values; the second lacks a second operand.

Common doubts

Can one queue contain duplicate values? Yes. Arrival order is still preserved. Removing one copy does not remove every equal value.

Does postfix reverse the numbers? No. It changes where operators appear. The evaluator preserves operand order by popping right before left.

Is a priority queue FIFO? Not in general. It removes according to priority, so it is a different data type from the FIFO queue here.

Does this code prefill the online compiler? No. Copy the code yourself, select Python and run it. Try the invalid expressions too and read the errors.

Keep practising

Data Structures lab: tested C programs gives implementation practice. Use the Online Compiler to run copied code. Return to BTech CSE Exam Notes for the wider subject guide.

References and checks

Additional checks: OpenDSA: stack and circular queue conventions; CS 240: circular indexes and postfix evaluation; Python deque: endpoint costs and bounded append behavior.

The wording, code and worked examples on this page are original. Sources used to check the rules: Python tutorial: stacks and queues; Python collections: deque; Runestone: postfix evaluation; Princeton: stacks, queues and amortized costs. Numeric traces and practice answers were independently run, including invalid-expression checks.

Previous: Episode 3: faster sorting | Current: Episode 4 | Next: Episode 5: linked lists | All episodes

Comments

Popular posts from this blog

Big Data Analytics Exam Prep

Process States in OS: Diagram, PCB and Context Switching

Python Mutable Default Arguments and Shallow Copies: Why Lists Keep Changing