Chapter 06
Stacks & Queues
4 topics · 3 sections · beginner-friendly study notes · Updated
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.
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.

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
CodePostfix 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]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.

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
Example
CodeCircular 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 resMonotonic 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.
Read more
Example
CodeNext 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 resBalanced 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.
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
CodeBracket 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 bestSolved examples
Evaluate postfix 5 3 2 * + 4 -.
Value
Formula Applied:—Approach note: For -, / pop b first then a and compute a op b.
Circular queue of size 5 (one slot sacrificed). front=3, rear=1. How many elements?
Count
Formula Applied:—Approach note: Full when (rear+1)%N == front; empty when front == rear.
Largest rectangle in histogram [2, 1, 5, 6, 2, 3].
Max area
Formula Applied:—Approach note: Width = i - new_top - 1; add sentinel 0 to flush.
Using a stack, check if "()[]{}" is balanced. Show the final stack state after processing.
Balanced? and stack
Formula Applied:—Approach note: Mismatch or leftover openings means invalid.
Real-world applications
Using Stacks & Queues in real projects
Undo/redo, browser history, compilers (parsing), OS scheduling, producer-consumer buffers, BFS.
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
- Stack LIFO O(1); queue FIFO O(1); call stack = recursion
- Postfix eval: pop b then a; infix->postfix by precedence/associativity
- Circular queue: (i+1)%N; full (rear+1)%N==front without a counter
- Monotonic stack: amortized O(n); next greater, histogram (sentinel 0)
- Balanced brackets: stack O(n); single type -> counter O(1)
Practice questions
Stack permutation of input 1,2,3: which output is impossible?
Postfix of a + b * c - d:
Number of valid bracket sequences with 3 pairs:
Circular queue size N with front/rear only: max elements?
Python efficient queue pop from front: