Module 5 · 18 min read · Free chapter
Arrays, stacks and queues
An array gives Θ(1) access because the address of A[i] is base + i × size. A stack is LIFO and a queue is FIFO, and both run in Θ(1) per operation on an array. A circular queue of size N is empty when front equals rear and full when (rear + 1) mod N equals front.
Start from zero: a pile of plates and a ration-shop line
At a wedding feast, clean steel plates are stacked one on top of another. The worker who washes a plate puts it on top of the pile, and a guest who wants a plate also takes it from the top. So the plate that went on last comes off first, and the plate at the bottom waits the longest.
Now walk to the ration shop in your mohalla. People join the line at the back, and the shopkeeper serves the person at the front. Here the first person to arrive is the first to leave, and nobody jumps ahead.
These two everyday rules are the two most used data structures in computing. The pile of plates is a stack, which follows Last In, First Out (LIFO). The ration line is a queue, which follows First In, First Out (FIFO).
Both are usually built on top of an array, a row of numbered boxes in memory. So this chapter starts with arrays, then builds stacks and queues on them, and ends with the clever variants that GATE likes to ask about.
Why it matters. Your browser's Back button is a stack of pages, and a printer that prints jobs in order is a queue. Compilers use stacks to read expressions and to run function calls, and operating systems use queues to share the CPU. Once LIFO and FIFO are clear, half of the data-structures syllabus becomes easy.
Arrays and address calculation
An array is a fixed-size collection of elements of the same type, stored in consecutive memory locations. Because every element has the same size of w bytes, the computer can jump straight to any element by arithmetic. If the array starts at base address B and its first index is L, then the address of A[i] is .
In C the first index is always 0, so the formula becomes . For example, if int A[50] starts at 2000 and an int takes 4 bytes, A[17] is at . This one multiplication is why reading A[i] takes time, whatever the size of the array.
Two-dimensional arrays. Memory is a single line of bytes, so a table of M rows and N columns must also be laid out in one line. Row-major order stores the whole of row 0, then row 1, and so on, and C does this. Column-major order stores the table column by column, and Fortran does this.
For an array A[lr..ur][lc..uc] with M rows and N columns, the address of A[i][j] is found as follows:
- In row-major order the address is , because full rows of N elements come before row i.
- In column-major order the address is , because full columns of M elements come first.
Worked example. Let A[1..10][1..15] be stored from base address 1000 with bytes, and find the address of A[4][7]. Here and . In row-major order, elements come before it, so the address is .
In column-major order, elements come first, so the address is . The same element sits at two different places, so always check which order the question states.
Why it matters. Address formulas are a sure-shot numerical in RRB JE, ISRO and GATE papers. They also explain real speed. A C loop that walks a matrix row by row touches neighbouring bytes, so thanks to the cache it runs faster than a loop that walks column by column.
The stack ADT and its array implementation
A stack is an abstract data type (ADT), which means it is defined by its operations and not by how it is stored. push(x) puts x on top, pop() removes and returns the top element, and peek() reads the top without removing it. Two checks complete the set: isEmpty() and, for a fixed-size stack, isFull().
The simplest implementation uses an array and one integer top, which holds the index of the current top element. An empty stack has , and a stack in an array of size MAX is full when .
#define MAX 100
int stack[MAX], top = -1;
void push(int x) {
if (top == MAX - 1) { printf("Overflow\n"); return; }
stack[++top] = x; /* move up, then store */
}
int pop(void) {
if (top == -1) { printf("Underflow\n"); return -1; }
return stack[top--]; /* read, then move down */
}
Each operation changes only top and one array cell, so push, pop and peek all take time. Pushing onto a full stack is called overflow, and popping from an empty one is called underflow. At any moment the stack holds elements.
Which outputs can a stack produce? Suppose 1, 2 and 3 arrive in that order, and at any moment you may push the next number or pop the top to the output. You can produce 1 2 3, 1 3 2, 2 1 3, 2 3 1 and 3 2 1, but never 3 1 2. Once 3 is popped, both 1 and 2 are still inside with 2 on top, so 1 cannot come out before 2.
In general, n inputs pushed in order can leave in different orders, the Catalan number, which gives 1, 2, 5, 14 and 42 for to . An output is impossible exactly when some value is followed later by a smaller value and then by a value between the two. That is the 3 … 1 … 2 pattern, and spotting it settles most such questions.
Why it matters. Undo in an editor, the Back button and the matching of brackets in code all use a stack. GATE often gives a sequence of pushes and pops and asks for the final top or for an impossible output. The 3 … 1 … 2 pattern answers such questions in seconds.
Infix, postfix and prefix expressions
We usually write infix expressions such as A + B, with the operator between its operands. Machines prefer postfix (A B +, also called reverse Polish) or prefix (+ A B, Polish notation). Postfix and prefix need no brackets and no precedence rules, because the position of each operator already fixes the order of work.
Infix to postfix with a stack. Scan the infix expression from left to right and keep a stack of operators:
- Send every operand straight to the output.
- Push a left bracket, and on a right bracket pop operators to the output until the matching left bracket, then discard both brackets.
- On an operator, first pop every stacked operator of higher precedence, or of equal precedence if the new one is left-associative, and then push the new operator.
- At the end, pop all remaining operators to the output.
The usual precedence puts the power operator (written ↑ here) highest, then * and ÷ (division), then + and −. The power operator is right-associative, so A ↑ B ↑ C means A ↑ (B ↑ C), and an incoming ↑ does not pop an ↑ already on the stack. The trace below converts A + B * C − D ÷ E.
| Step | Operator stack | Output so far |
|---|---|---|
| read A | empty | A |
| read +, push | + | A |
| read B | + | A B |
| read *, higher than +, push | + * | A B |
| read C | + * | A B C |
| read −, pop * and +, push − | − | A B C * + |
| read D, then ÷, push / | − ÷ | A B C * + D |
| read E | − ÷ | A B C * + D E |
| end, pop all | empty | A B C * + D E ÷ − |
So A + B * C − D ÷ E becomes A B C * + D E ÷ −. With brackets, (A + B) * (C − D) becomes A B + C D − *, and its prefix form is * + A B − C D.
Evaluating postfix. Scan from left to right with a stack of operands. Push each number; on an operator, pop two values, apply the operator and push the result. The first value popped is the right operand, so for 8 2 / you compute and not .
Worked example. Evaluate 6 2 3 + − 3 8 2 ÷ + *. The stack grows to 6 2 3, the + makes it 6 5, and the − gives . Next it becomes 1 3 8 2, the ÷ leaves 1 3 4, the + leaves 1 7, and the final * gives 7, with at most 4 values on the stack at any moment.
A prefix expression is evaluated the same way but scanned from right to left, and then the first value popped is the left operand. For − * 2 3 4, push 4, 3 and 2; the * pops 2 and 3 to give 6, and the − pops 6 and 4 to give .
Why it matters. Compilers turn your infix formulas into postfix-like code, and many old calculators worked in postfix directly. GATE asks for the converted string, the final value or the largest stack size during evaluation, so practise all three.
Recursion and the call stack
A function that calls itself is recursive. Every recursive definition needs a base case that stops the calls and a recursive case that moves towards it. In C the factorial is the classic example.
int fact(int n) {
if (n <= 1) return 1; /* base case */
return n * fact(n - 1); /* recursive case */
}
How does the machine remember where it was? Each call creates an activation record, or stack frame, holding the parameters, the local variables and the return address, and pushes it on the call stack. When a call finishes, its frame is popped and control returns to the caller, which is the LIFO rule again.
For fact(4), the frames fact(4), fact(3), fact(2) and fact(1) pile up, so the maximum depth is 4. Then fact(1) returns 1, fact(2) returns 2, fact(3) returns 6 and fact(4) returns 24, in the reverse order of the calls. So a recursion of depth n uses stack space even though the function declares no array, and very deep recursion ends in a stack overflow.
Tracing a GATE-style function. Consider a function that prints on the way down and again on the way back.
void f(int n) {
if (n == 0) return;
printf("%d ", n);
f(n - 1);
printf("%d ", n);
}
The call f(3) prints 3 2 1 on the way down, and then 1 2 3 as the frames are popped, so the output is 3 2 1 1 2 3. Code before the recursive call runs in calling order, and code after it runs in reverse order. That single rule solves most recursion-tracing questions.
Any recursion can be turned into a loop with an explicit stack. The two-call Fibonacci function fib(n) = fib(n - 1) + fib(n - 2) is a warning, because it makes an exponential number of calls although its stack depth is only about n.
Why it matters. Every function call in every program uses this stack, so it explains both recursion bugs and attacks that overwrite return addresses. In exams, the output of a recursive function and its maximum stack depth are asked again and again.
Queues and the circular queue
A queue supports enqueue(x), which adds x at the rear, and dequeue(), which removes the element at the front. A simple array version keeps two indices, front and rear, and moves each one forward on its own operation. Both operations take time.
The trouble with this linear version is wasted space. After many enqueues and dequeues both indices march towards the end of the array, so the queue can report "full" while the cells at the start are empty.
The clean fix is the circular queue, which treats the array of size N as a ring so that index is followed by index 0. Every move becomes or . In the common convention, front is the index of the first element and rear is the index where the next element will go.
#define N 5
int q[N], front = 0, rear = 0;
int enqueue(int x) {
if ((rear + 1) % N == front) return 0; /* full */
q[rear] = x; rear = (rear + 1) % N; return 1;
}
int dequeue(int *x) {
if (front == rear) return 0; /* empty */
*x = q[front]; front = (front + 1) % N; return 1;
}
Now a puzzle appears, because could mean either empty or full. The usual answer is to leave one cell always unused. Then the queue is empty when and full when , so an array of size N holds at most elements. The other answer is to keep a separate count, which lets all N cells be used.
Worked example. Take with . Enqueue 10, 20, 30 and 40: they fill cells 0 to 3, rear becomes 4, and , so the queue is full with 4 elements. Dequeue twice, so ; then enqueue 50 into cell 4 and 60 into cell 0, and rear becomes 1, which is full again because .
The number of elements at any moment is . In the last state that gives , which matches 30, 40, 50 and 60.
Why it matters. Keyboard buffers, printer spools, network routers and CPU schedulers use circular queues because they never shift data. GATE likes to state the full and empty conditions in four slightly different ways and ask which pair is right, so learn the one-empty-cell rule exactly.
Deque, priority queue and a queue from two stacks
A deque (double-ended queue) allows insertion and deletion at both ends. An input-restricted deque allows insertion at only one end but deletion at both, and an output-restricted deque allows deletion at only one end but insertion at both. A deque can act as a stack or as a queue, so it is the most general of the three.
A priority queue serves the element with the highest priority first, not the one that came first, just as a hospital emergency ward sees the most serious patient first. Its main operations are insert and delete-min (or delete-max). The table compares three ways of building it.
| Implementation | Insert | Delete-min |
|---|---|---|
| Unsorted array or list | ||
| Sorted array or list | ||
| Binary heap |
The binary heap wins on balance, and it is built step by step in trees, binary search trees and binary heaps.
A queue from two stacks. GATE often asks how to build a FIFO queue using only LIFO stacks. Keep two stacks, for input and for output:
- To enqueue x, push x onto .
- To dequeue, first check , and if it is empty, pop every element of and push it onto ; then pop .
Moving the elements reverses their order, so the oldest element ends on top of . A single dequeue can cost when it triggers the move, but every element is pushed and popped at most twice, once in each stack. So n operations cost at most about stack operations, which is amortised per operation.
Worked example. Enqueue 1, 2 and 3, then dequeue, then enqueue 4, then dequeue twice. The first dequeue moves 3, 2 and 1 from into so that 1 is on top, and returns 1. The value 4 goes to , the next two dequeues pop 2 and 3 from , and only a later dequeue would need to move 4 across.
Why it matters. Priority queues drive shortest-path algorithms, job schedulers and event simulations. The two-stack queue is a favourite GATE and interview question, because it tests whether you can count amortised cost instead of the cost of one step.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university-level tests ask about this topic in four ways:
- They ask you to define the stack and queue ADTs and write their array implementations in C, with overflow and underflow checks.
- They ask you to convert an infix expression to postfix or prefix and to evaluate a postfix expression, showing the stack at each step.
- They ask you to explain why a circular queue is needed and to state its full and empty conditions.
- They ask you to design one structure from another, such as a queue from two stacks, and to analyse its cost.
Practice questions (our own, not previous-year questions).
- Write C functions for push and pop on an array stack, and explain overflow and underflow with an example. (10 marks)
- Convert
(A + B) * C − D ÷ (E + F)to postfix and to prefix, showing the operator stack at each step. (10 marks) - Show how a queue can be implemented using two stacks, and prove that the amortised cost of each operation is constant. (15 marks)
Answer plan for question 3.
- Begin by stating that a queue is FIFO while a stack is LIFO, so reversing an order twice restores the arrival order.
- Describe the two stacks, with receiving new elements and giving out old ones.
- Write enqueue as a single push onto , which takes constant time.
- Write dequeue as a pop from , where all of is first moved into only when is empty.
- Show with a short example that the oldest element always reaches the top of .
- Argue that each element is pushed twice and popped twice in its life, so n operations cost at most stack steps and the amortised cost is .
- Conclude that a single dequeue can still take in the worst case, and say where such a design is useful.
Quick revision
- An array gives access because the address of
A[i]is . - Row-major uses the number of columns, , and C uses row-major order.
- Column-major uses the number of rows, .
- A stack is LIFO, and with top = −1 for empty it is full at .
- Infix to postfix uses an operator stack, and evaluation uses an operand stack where the first value popped is the right operand.
- Each function call pushes a frame, so recursion of depth n uses stack space.
- A circular queue is empty when and full when , holding elements.
- A priority queue on a binary heap gives insert and delete.
- A queue from two stacks costs amortised per operation, though one dequeue can cost .
- Inputs 1 to n pushed in order give a Catalan number of outputs, 5 for , and 3 1 2 is impossible.