Programming & DSA
Stacks & Queues
Stacks and queues give quick marks: know the LIFO/FIFO rules, evaluate postfix without errors, convert infix to postfix with precedence rules, and write circular queue conditions correctly.
GATE CSE stacks and queues — LIFO/FIFO, array and linked implementations, postfix evaluation, infix-to-postfix conversion, circular queue conditions, deque, and stack permutations with samples and drills.
Learning outcomes
- Apply stack (LIFO) and queue (FIFO) operations, overflow, and underflow conditions to traces
- Evaluate postfix and prefix expressions and convert infix expressions to postfix with an operator stack
- Write correct empty/full conditions and element counts for a circular queue
- Count stack permutations and implement a queue with stacks (and vice versa)
Stack ADT (LIFO)
- A stack allows insertion (push) and deletion (pop) only at one end, the top. The last element pushed is the first popped: Last In First Out. peek/top reads the top without removing it.
- Array implementation: top = -1 means empty; push does a[++top] = x; pop returns a[top--]; full when top == MAX − 1. Pushing on a full stack is overflow; popping from an empty stack is underflow.
- Linked implementation: push and pop at the head of a singly linked list; there is no fixed capacity and every operation is O(1).
- All of push, pop, peek, and isEmpty are O(1) in both implementations.
- Applications: function-call (activation record) stack and recursion, undo, parentheses/bracket matching, expression evaluation and conversion, DFS (explicit stack), and backtracking.
- Balanced-parentheses check: push every opening bracket; on a closing bracket pop and compare; the string is balanced if the stack is empty at the end and no pop was on an empty stack.
| Operation | Array stack | Linked stack |
|---|---|---|
| push | O(1) (overflow if full) | O(1) |
| pop | O(1) (underflow if empty) | O(1) |
| peek | O(1) | O(1) |
| Search | O(n) | O(n) |
Worked example
Problem. Push 1, 2, 3, pop, push 4, pop, pop. What is on top now?
Solution. Push 1,2,3 → [1,2,3]; pop removes 3 → [1,2]; push 4 → [1,2,4]; pop removes 4; pop removes 2 → [1]. The top is 1.
Queue ADT and circular queue
- A queue inserts at the rear (enqueue) and deletes at the front (dequeue): First In First Out. Both operations are O(1) with a front and rear pointer (array) or head and tail pointers (linked list).
- Linked implementation: enqueue at the tail and dequeue at the head. (Enqueue at the head and dequeue at the tail would need O(n) in a singly list.)
- A simple linear array queue wastes space because front moves right and freed cells are never reused. A circular queue wraps indices using modulo: rear = (rear + 1) % N, front = (front + 1) % N.
- Common GATE convention: front points to the slot just before the first element and rear points to the last element. Empty when front == rear. Full when (rear + 1) % N == front. One slot is sacrificed, so the capacity is N − 1.
- Number of elements in this convention = (rear − front + N) % N.
- If a separate count variable is kept (or the front index points to the first element with a count), all N slots can be used. Read the convention given in the question.
- A deque (double-ended queue) allows insert and delete at both ends; restricted forms are input-restricted and output-restricted deques. A priority queue serves the highest priority element first (implemented with a heap, not FIFO).
Formulas to remember
-
Circular advance: i = (i + 1) % N -
Empty: front == rear; Full: (rear + 1) % N == front -
Count = (rear − front + N) % N, capacity = N − 1
Worked example
Problem. Circular queue of N = 8 slots, front = 5, rear = 2 (front points before the first element). How many elements?
Solution. (2 − 5 + 8) % 8 = 5 elements.
Postfix and prefix evaluation
- Infix places the operator between operands (A + B), prefix (Polish) before them (+ A B), postfix (reverse Polish) after them (A B +). Postfix and prefix need no parentheses and no precedence rules.
- Postfix evaluation: scan left to right; push operands; on an operator pop the top two values — the first popped is the RIGHT operand b and the second is the LEFT operand a — compute a op b and push the result. The final stack holds the answer.
- Prefix evaluation: scan right to left; push operands; on an operator pop the first value as the LEFT operand and the second as the RIGHT operand (so the operand order is a op b with a popped first).
- The order of operands matters for - / ^: for the postfix 8 2 /, the answer is 8 / 2 = 4, not 2 / 8.
- Stack depth for evaluating a valid postfix expression never exceeds the number of operands; a valid expression with n operands has n − 1 binary operators.
- To go from postfix to prefix (or back) rebuild the expression tree: postorder traversal gives postfix and preorder gives prefix.
Worked example
Problem. Evaluate the postfix expression 5 6 2 + * 12 4 / -.
Solution. 6 + 2 = 8; 5 × 8 = 40; 12 / 4 = 3; 40 − 3 = 37.
Infix to postfix conversion
- Scan the infix string left to right. Operands go directly to the output. An operator is pushed on the stack after popping every stack operator with higher precedence, or equal precedence if the operator is left-associative.
- ( is always pushed; on ) pop operators to the output until ( is found and discard both parentheses. At the end pop everything left.
- Precedence: ^ (highest, right-associative) > * and / > + and − (left-associative). Because ^ is right-associative, a ^ b ^ c becomes a b c ^ ^ — equal-precedence ^ is NOT popped.
- Left-associative example: a − b − c becomes a b − c − (equal precedence operators are popped first).
- The relative order of operands never changes between infix and postfix; only operators move.
- Maximum stack depth is bounded by the nesting of parentheses plus pending lower-precedence operators; GATE sometimes asks for the maximum stack size during conversion.
| Infix | Postfix | Prefix |
|---|---|---|
| A + B * C | A B C * + | + A * B C |
| (A + B) * C | A B + C * | * + A B C |
| A − B − C | A B − C − | − − A B C |
| A ^ B ^ C | A B C ^ ^ | ^ A ^ B C |
| A * (B + C) / D | A B C + * D / | / * A + B C D |
Worked example
Problem. Convert A + B * C − D / E to postfix.
Solution. B * C has priority, D / E also: A B C * + D E / −. Check: A + (B*C) gives A B C * +, then subtract (D/E) gives A B C * + D E / −.
Stack permutations and implementations from each other
- If the input 1, 2, ..., n is pushed in order and pops may interleave arbitrarily, the number of distinct output permutations is the Catalan number C_n = (1/(n+1)) × C(2n, n). For n = 3 it is 5, for n = 4 it is 14.
- For n = 3 (input 1 2 3) the only impossible output is 3 1 2: after outputting 3 the stack holds 1 below 2, so 2 must come out before 1.
- Test for validity: an output permutation is possible if there is no triple i < j < k in the input with outputs appearing in the order k, i, j (the 312 pattern).
- Queue using two stacks: push all enqueues onto stack S1; for dequeue, if S2 is empty pour all of S1 into S2, then pop S2. Each element moves at most twice, so the amortised cost per operation is O(1) although a single dequeue can be O(n).
- Stack using two queues: either make push O(n) (move elements after inserting) or pop O(n); one operation must cost O(n).
- Reversing a sequence needs a stack; a queue followed by a stack gives the reverse order. A stack can also check palindromes by comparing the first half with the reversed second half.
Formulas to remember
-
Catalan: C_n = (1/(n+1)) × C(2n, n) → 1, 1, 2, 5, 14, 42 ... -
Distinct stack permutations of n pushes = C_n
Worked example
Problem. Input order 1 2 3 into a stack. Is the output 3 1 2 possible?
Solution. No. To output 3 first, 1 and 2 are on the stack with 2 on top; 2 must be popped before 1, so 3 2 1 is possible but 3 1 2 is not.
GATE exam tricks — stacks and queues
- Validity of a postfix string: scanning left to right, the count of operands seen must always exceed the count of operators seen, and at the end operands = operators + 1 (for binary operators). Otherwise it underflows or leaves extra values.
- Order of popped operands: right operand is popped FIRST in postfix. Mix this up and every subtraction, division, or power in the question flips the answer.
- Infix -> postfix by hand: fully parenthesise using precedence/associativity, then move each operator to just after its closing bracket. Operand order never changes.
- Max stack size during conversion = the largest number of operators and ( symbols held at once; count it while you convert.
- Stack permutations: the forbidden pattern is the 312 pattern (k, i, j with i < j < k in input order). For input 1 2 3 4, the count of valid outputs is C4 = 14.
- Circular queue questions always depend on the convention: (a) front before first, rear at last: capacity N-1, count = (rear - front + N) % N; (b) with a count variable: all N slots usable. Write the convention down first.
- Two-stack queue: amortised O(1) per operation, worst case single dequeue O(n). Two-queue stack: one of push/pop must be O(n).
- Standard pairings: DFS and recursion use a stack, BFS uses a queue, priority queue uses a heap, parenthesis matching uses a stack, and "undo" uses a stack.
Worked example
Problem. Is 3 4 + * 5 a valid postfix expression?
Solution. Push 3, push 4, + gives 7 (one value on the stack). The * needs two operands but only one is available, so it underflows. The expression is invalid (at the * token, operands seen = 2 but operators seen = 2, violating operands > operators).
Worked trace: circular queue with N = 5
- Use the convention front = index before the first element, rear = last element; both start at 0 so the queue is empty.
- Enqueue: rear = (rear + 1) % N, then store at a[rear]. Dequeue: front = (front + 1) % N, then read a[front].
- Check full before enqueue with (rear + 1) % N == front; check empty before dequeue with front == rear.
Worked example
Problem. N = 5, front = rear = 0. Operations: enq A, enq B, enq C, enq D, deq, deq, enq E, enq F. Final front, rear, and element count? Is the queue full?
Solution. After four enqueues rear = 4 (A..D at 1..4). Two dequeues remove A and B: front = 2. enq E: rear = (4+1)%5 = 0, E at index 0. enq F: rear = 1, F at index 1. Final front = 2, rear = 1, count = (1 - 2 + 5) % 5 = 4 = N - 1, and (rear + 1) % 5 = 2 == front, so the queue is full.
Exam tips
- For postfix evaluation, remember the first popped value is the right operand.
- Write the circular-queue convention given in the question before using any formula.
- For infix to postfix, keep ^ right-associative and all other binary operators left-associative.
- Draw the stack after each token when asked for maximum depth or final contents.
- The number of possible stack output permutations uses Catalan numbers: n = 3 gives 5, n = 4 gives 14.
10 GATE-style MCQs for Stacks & Queues with full explanations. Attempt each question before revealing the answer.
What is the value of the postfix expression 8 2 3 ^ / 2 3 * + 5 1 * − ?
Show answer & explanation
Answer: B
2 3 ^ = 8; 8 / 8 = 1; 2 3 * = 6; 1 + 6 = 7; 5 1 * = 5; 7 − 5 = 2.
The postfix form of the infix expression A + B * C is:
Show answer & explanation
Answer: B
* has higher precedence, so B C * is formed first and then added to A: A B C * +.
Operations on an empty stack: push 1, push 2, push 3, pop, push 4, pop, pop. What is the top element afterwards?
Show answer & explanation
Answer: A
After the pushes [1,2,3]; pop → [1,2]; push 4 → [1,2,4]; pop → [1,2]; pop → [1]. The top is 1.
A circular queue uses N = 8 slots, front points to the slot before the first element, and rear points to the last element. If front = 5 and rear = 2, how many elements are stored?
Show answer & explanation
Answer: B
Count = (rear − front + N) % N = (2 − 5 + 8) % 8 = 5.
Integers 1, 2, 3 are pushed in this order onto a stack, with pops allowed at any time. Which output sequence is NOT possible?
Show answer & explanation
Answer: D
To output 3 first, both 1 and 2 are on the stack with 2 above 1, so 2 must precede 1. 3 1 2 is impossible.
How many distinct output permutations are possible when the sequence 1, 2, 3, 4 is passed through a stack (push in order, pops interleaved)?
Show answer & explanation
Answer: B
The count is the Catalan number C4 = (1/5) × C(8,4) = 70/5 = 14.
A queue is implemented using two stacks. The amortised cost of each enqueue/dequeue operation is:
Show answer & explanation
Answer: A
Each element is pushed and popped at most twice in total (once per stack), so the total work for n operations is O(n).
For a stack implemented as a singly linked list, the best place to push and pop (so both are O(1)) is:
Show answer & explanation
Answer: B
At the head both insert and delete are O(1). Deleting at the tail of a singly list needs O(n).
The postfix expression for the infix A ^ B ^ C, with ^ right-associative, is:
Show answer & explanation
Answer: B
A ^ (B ^ C): the operator ^ of B and C is output first, giving A B C ^ ^.
While converting a + (b * (c − d)) to postfix with an operator stack (parentheses are pushed too), what is the maximum number of symbols on the stack at any time?
Show answer & explanation
Answer: C
The stack grows: [+], [+,(], [+,(,*], [+,(,*,(], [+,(,*,(,−] — five symbols — then shrinks as parentheses close.
Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.
Evaluate the postfix expression 2 3 4 * +.
Show answer & explanation
Answer: B) 14
3 × 4 = 12; 2 + 12 = 14.
Evaluate the postfix expression 10 2 8 * + 3 −.
Show answer & explanation
Answer: A) 23
2 × 8 = 16; 10 + 16 = 26; 26 − 3 = 23.
Evaluate the prefix expression − * 2 3 4.
Show answer & explanation
Answer: A) 2
The expression is (2 × 3) − 4 = 6 − 4 = 2.
The postfix form of (A + B) * C is:
Show answer & explanation
Answer: B) A B + C *
Parentheses force A + B first: A B +, then multiply by C: A B + C *.
Popping from an empty stack is called:
Show answer & explanation
Answer: B) Underflow
Removing from an empty structure is underflow; pushing on a full one is overflow.
A circular array queue with N = 5 slots uses the convention that one slot is left empty to distinguish full from empty. The maximum number of elements it can hold is:
Show answer & explanation
Answer: B) 4
The capacity is N − 1 = 4.
Which pair correctly matches the traversal with the data structure it uses?
Show answer & explanation
Answer: B) BFS - queue, DFS - stack
Breadth-first search processes nodes in FIFO order (queue); depth-first search uses LIFO order (explicit stack or recursion).
Enqueue 1, 2, 3; dequeue; enqueue 4; dequeue. Which element is at the front of the queue now?
Show answer & explanation
Answer: C) 3
[1,2,3] → dequeue removes 1 → [2,3] → enqueue 4 → [2,3,4] → dequeue removes 2 → [3,4]. Front is 3.
How many distinct permutations can be obtained from the input 1, 2, 3 using one stack?
Show answer & explanation
Answer: B) 5
C3 = 5; out of the 6 permutations only 3 1 2 is impossible.
The postfix form of A + B * C − D / E is:
Show answer & explanation
Answer: A) A B C * + D E / −
A + (B*C) gives A B C * +; D / E gives D E /; subtracting yields A B C * + D E / −.
Topic FAQs
What is the difference between stack overflow and stack underflow?
Overflow is pushing onto a full stack; underflow is popping from an empty stack.
Why is a circular queue better than a linear array queue?
It reuses freed cells at the front by wrapping indices with modulo, so the space is not wasted after repeated enqueue and dequeue operations.
Why does postfix notation need no parentheses?
The position of each operator already fixes the order of evaluation, so no precedence rules or brackets are needed.
How do you tell whether a circular queue is full or empty when front == rear?
Either sacrifice one slot (full when (rear + 1) % N == front, empty when front == rear) or keep a separate element count.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.