Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 06

Stacks & Queues

4 topics · 3 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Detailed notes with diagrams

A full topic lesson from this chapter — diagram, table, examples and a quick check.

A stack is LIFO and a queue is FIFO; both support O(1) core operations.

Stacks power parsing, recursion and monotonic-stack problems; queues power BFS, scheduling and buffering, with circular arrays avoiding wasted space.

Stack/queue reasoning underlies DFS, BFS, function calls and many O(n) interview solutions that replace nested loops.

Undo/redo, browser history, compilers (parsing), OS scheduling, producer-consumer buffers, BFS.

1

Stack Data Structure (LIFO)

A stack allows insertion (push) and removal (pop) only at one end, the top, so the last element pushed is the first popped. push, pop, peek and isEmpty are O(1).

In short: Like a pile of plates: you add and remove only from the top.

Stack LIFO: push and pop from the top
Stack LIFO: push and pop from the top

Think about it

GATE regularly asks stack permutations, postfix evaluation and stack-based recursion tracing.

Array implementation: top index, push O(1) amortized (resize), overflow when full in fixed arrays; linked implementation: push/pop at head, O(1) worst case, extra pointer memory.

Pop on empty gives underflow.

The call stack is a stack of frames; recursion = implicit stack, so any recursion can be converted to an explicit stack.

Applications: expression evaluation (postfix with operand stack), infix-to-postfix with an operator stack and precedence, DFS, undo, backtracking, next greater element.

Postfix evaluation: scan tokens, push operands, on operator pop b then a, push a op b (order matters for - and /).

Infix to postfix: operands output directly; operator pops while top has higher precedence (or equal and left-associative); ( pushed, ) pops till (.

^ is right-associative.

Min stack: store (value, current_min) pairs to get getMin in O(1).

Stack permutation: with input 1..

n, an output order is valid iff no pattern 3-1-2 (e.

g.

3 1 2 is impossible); number of valid permutations is the Catalan number C(2n,n)/(n+1).

Key points

  • Push / Pop / Peek: Insert top / remove top / read top.
  • Underflow / Overflow: Pop on empty / push on full.
  • Postfix: Operator after operands: a b + c *.

Example

Code
Postfix evaluation, conversion, min stack:
def eval_postfix(tokens):
    st = []
    for t in tokens:
        if t in '+-*/':
            b, a = st.pop(), st.pop()
            st.append({'+': a + b, '-': a - b, '*': a * b,
                       '/': int(a / b)}[t])
        else:
            st.append(int(t))
    return st[0]

def infix_to_postfix(expr):
    prec = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
    out, st = [], []
    for c in expr:
        if c.isalnum(): out.append(c)
        elif c == '(': st.append(c)
        elif c == ')':
            while st[-1] != '(': out.append(st.pop())
            st.pop()
        else:
            while (st and st[-1] != '(' and
                   (prec[st[-1]] > prec[c] or
                    (prec[st[-1]] == prec[c] and c != '^'))):
                out.append(st.pop())
            st.append(c)
    return out + st[::-1]

class MinStack:
    def __init__(self): self.s = []
    def push(self, x): self.s.append((x, min(x, self.s[-1][1]) if self.s else x))
    def pop(self): return self.s.pop()[0]
    def get_min(self): return self.s[-1][1]
2

Queue & Circular Queue

A queue is FIFO: enqueue at the rear, dequeue at the front, both O(1). A circular queue stores elements in a fixed array and wraps indices with modulo so freed front slots are reused.

In short: People in a line: first in, first out. A circular queue loops the array so no space is wasted.

Queue FIFO: enqueue at rear, dequeue at front
Queue FIFO: enqueue at rear, dequeue at front

Think about it

Full/empty conditions of circular queues are a recurring GATE question; BFS depends on queues.

Linear array queue wastes slots after dequeues (front keeps moving right).

Circular: rear = (rear + 1) % N, front = (front + 1) % N. Ambiguity: front == rear can mean empty or full.

Fixes: keep a size counter, or sacrifice one slot so full is (rear + 1) % N == front and empty is front == rear (capacity N-1).

With a count, capacity is N. Deque (double-ended) allows O(1) at both ends (Python collections.

deque, Java ArrayDeque).

Priority queue is not FIFO (see heaps).

Queue using two stacks: enqueue pushes to in-stack; dequeue pops from out-stack, refilling it from in-stack when empty: amortized O(1) per operation.

Stack using two queues: O(n) push or pop.

Applications: BFS, level-order traversal, task scheduling (round robin), sliding window maximum using a monotonic deque in O(n).

Python list.

pop(0) is O(n), so use deque.

popleft() for O(1).

Key points

  • Front / Rear: Dequeue end / enqueue end.
  • Deque: Double-ended queue; insert/remove at both ends.
  • Circular buffer: Fixed array with wrap-around indices.

Example

Code
Circular queue, two-stack queue, sliding max:
class CircularQueue:
    def __init__(self, n):
        self.a, self.n = [None] * n, n
        self.front = self.size = 0
    def enqueue(self, x):
        if self.size == self.n: raise OverflowError
        self.a[(self.front + self.size) % self.n] = x
        self.size += 1
    def dequeue(self):
        if self.size == 0: raise IndexError('underflow')
        x = self.a[self.front]
        self.front = (self.front + 1) % self.n
        self.size -= 1
        return x

class QueueTwoStacks:
    def __init__(self): self.inn, self.out = [], []
    def enqueue(self, x): self.inn.append(x)
    def dequeue(self):
        if not self.out:
            while self.inn: self.out.append(self.inn.pop())
        return self.out.pop()

from collections import deque
def sliding_max(a, k):             # monotonic deque, O(n)
    dq, res = deque(), []
    for i, x in enumerate(a):
        while dq and a[dq[-1]] <= x: dq.pop()
        dq.append(i)
        if dq[0] <= i - k: dq.popleft()
        if i >= k - 1: res.append(a[dq[0]])
    return res
3

Monotonic Stack Pattern

A monotonic stack keeps its elements in increasing or decreasing order by popping elements that violate the order before pushing a new one. Each element is pushed and popped at most once, so total time is O(n).

In short: A stack that stays sorted; elements that can never be the answer are thrown away immediately.

Think about it

Replaces O(n^2) nested scans with O(n); very common in interviews.

Next greater element: scan right to left (or left to right storing indices), maintain a decreasing stack; for each x pop while top <= x, answer is the top (or -1), then push x.

When x arrives in a left-to-right scan, every popped smaller element has found its next greater = x.

Daily temperatures, stock span, previous smaller element, and circular next greater (iterate 2n with index % n) use the same pattern.

Largest rectangle in histogram: keep an increasing stack of indices; when a shorter bar arrives, pop and compute area = height[popped] * (i - stack[-1] - 1) (width between the new top and i); append a sentinel 0 at the end to flush.

O(n).

Maximal rectangle in a binary matrix: histogram per row, O(RC).

Trapping rain water also has a stack solution.

Amortized argument: n pushes, at most n pops.

Store indices rather than values when you need distances.

Key points

  • Monotonic: Elements always increasing or always decreasing from bottom to top.
  • Next greater element: First larger value to the right.

Example

Code
Next greater and histogram:
def next_greater(a):
    res, st = [-1] * len(a), []        # st holds indices, values decreasing
    for i, x in enumerate(a):
        while st and a[st[-1]] < x:
            res[st.pop()] = x
        st.append(i)
    return res

def largest_rectangle(h):
    st, best = [], 0
    for i, x in enumerate(h + [0]):    # sentinel flushes the stack
        while st and h[st[-1]] >= x:
            height = h[st.pop()]
            left = st[-1] if st else -1
            best = max(best, height * (i - left - 1))
        st.append(i)
    return best

def daily_temperatures(t):
    res, st = [0] * len(t), []
    for i, x in enumerate(t):
        while st and t[st[-1]] < x:
            j = st.pop(); res[j] = i - j
        st.append(i)
    return res
4

Balanced Parentheses Check

A string of brackets is balanced if every opener has a matching closer of the same type in the correct nesting order. Use a stack: push openers, on a closer the top must be its matching opener; at the end the stack must be empty.

In short: Every closing bracket must close the most recent unclosed opening bracket.

Stack remembers what is still open

Think about it

Entry-level stack question that appears in screening rounds and GATE (stack-needed language recognition: balanced brackets are context-free, not regular).

Time O(n), space O(n).

Failure cases: closer with empty stack, mismatched type (e.

g.

"(]"), leftover openers at the end.

With only one bracket type a counter suffices (O(1) space): count never negative and ends at 0.

Minimum additions to balance: track open count and number of unmatched closers; answer = unmatched_closers + remaining_open.

Longest valid parentheses: stack of indices with base -1, or two-pass counter in O(1) space.

Remove minimum invalid parentheses uses BFS/backtracking.

Number of valid sequences with n pairs is Catalan C_n = C(2n,n)/(n+1).

The same stack idea validates HTML tags and evaluates nested expressions.

Remember to also ignore non-bracket characters when parsing code.

Key points

  • Matching pair: () [] {} with correct order.
  • Catalan number: Counts balanced sequences of n pairs.

Example

Code
Bracket problems:
def is_balanced(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    st = []
    for c in s:
        if c in '([{':
            st.append(c)
        elif c in pairs:
            if not st or st.pop() != pairs[c]:
                return False
    return not st

def min_add_to_balance(s):
    open_, add = 0, 0
    for c in s:
        if c == '(':
            open_ += 1
        elif open_:
            open_ -= 1
        else:
            add += 1
    return add + open_

def longest_valid(s):
    st, best = [-1], 0
    for i, c in enumerate(s):
        if c == '(':
            st.append(i)
        else:
            st.pop()
            if st: best = max(best, i - st[-1])
            else: st.append(i)
    return best

Solved examples

Example 01 · Basic

Evaluate postfix 5 3 2 * + 4 -.

Given Data:
    Required To Find:

    Value

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: push 5, 3, 2.
    Step 2: * -> 3*2=6; stack [5,6].
    Step 3: + -> 11.
    Step 4: push 4; - -> 11-4=7.
    Final Answer: 7

    Approach note: For -, / pop b first then a and compute a op b.

    Example 02 · Intermediate

    Circular queue of size 5 (one slot sacrificed). front=3, rear=1. How many elements?

    Given Data:
      Required To Find:

      Count

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: (1 - 3 + 5) % 5 = 3.
      Step 2: Capacity is 4 usable slots, so not full.
      Final Answer: 3 elements

      Approach note: Full when (rear+1)%N == front; empty when front == rear.

      Example 03 · Advanced

      Largest rectangle in histogram [2, 1, 5, 6, 2, 3].

      Given Data:
        Required To Find:

        Max area

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: i=0 (2): push idx0. i=1 (1): pop idx0 (h=2), left=-1, width = 1-(-1)-1 = 1, area 2; push idx1.
        Step 2: Push idx2 (5), idx3 (6). i=4 (2): pop idx3 (h=6), left=2, width 1, area 6; pop idx2 (h=5), left=1, width = 4-1-1 = 2, area 10; push idx4.
        Step 3: i=5 (3): push idx5. Sentinel i=6 (0): pop idx5 (h=3, width 1, area 3); pop idx4 (h=2, left=1, width 4, area 8); pop idx1 (h=1, left=-1, width 6, area 6).
        Step 4: Max area = 10 (bars of heights 5 and 6, limited by height 5).
        Final Answer: 10

        Approach note: Width = i - new_top - 1; add sentinel 0 to flush.

        Example 04 · Basic

        Using a stack, check if "()[]{}" is balanced. Show the final stack state after processing.

        Given Data:
          Required To Find:

          Balanced? and stack

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Push opening brackets
          Step 2: On closing, pop and match type
          Step 3: String ends with empty stack → balanced
          Final Answer: Balanced; stack empty at end

          Approach note: Mismatch or leftover openings means invalid.

          Real-world applications

          DSA

          Using Stacks & Queues in real projects

          Undo/redo, browser history, compilers (parsing), OS scheduling, producer-consumer buffers, BFS.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: In a circular queue front == rear always means empty.

          Why this is wrong: With all slots usable it can also mean full.

          ✅ Verified Truth: Use a size counter or leave one slot empty to disambiguate.

          ⚠️ Exam Tip: GATE: capacity N-1 when using only front/rear indices.

          ❌ Myth: A monotonic stack is O(n^2) because of the inner while loop.

          Why this is wrong: Each element is pushed once and popped at most once.

          ✅ Verified Truth: Amortized O(n).

          ⚠️ Exam Tip: State the push/pop counting argument.

          ❌ Myth: A queue using two stacks makes dequeue always O(n).

          Why this is wrong: Transfer happens only when the out-stack is empty; each element moves once.

          ✅ Verified Truth: Amortized O(1) per operation.

          ⚠️ Exam Tip: Worst single dequeue is O(n).

          Revision notes

          A stack is LIFO and a queue is FIFO; both support O(1) core operations. Stacks power parsing, recursion and monotonic-stack problems; queues power BFS, scheduling and buffering, with circular arrays avoiding wasted space.

          High-Yield Quick Revision Points

          1. Stack LIFO O(1); queue FIFO O(1); call stack = recursion
          2. Postfix eval: pop b then a; infix->postfix by precedence/associativity
          3. Circular queue: (i+1)%N; full (rear+1)%N==front without a counter
          4. Monotonic stack: amortized O(n); next greater, histogram (sentinel 0)
          5. Balanced brackets: stack O(n); single type -> counter O(1)

          Practice questions

          Question 1 · MCQ (GATE)

          Stack permutation of input 1,2,3: which output is impossible?

          Question 2 · MCQ (GATE)

          Postfix of a + b * c - d:

          Question 3 · MCQ (GATE)

          Number of valid bracket sequences with 3 pairs:

          Question 4 · MCQ (GATE)

          Circular queue size N with front/rear only: max elements?

          Question 5 · MCQ (Interview)

          Python efficient queue pop from front: