Computer Science and IT‹›⌂ 0:00 studied

Module 5 · 18 min read · Free chapter

Arrays, stacks and queues

In short

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.

What are you preparing for? We show the practice and previous year questions of your exam.

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 B+(i−L)×wB + (i - L) \times w.

In C the first index is always 0, so the formula becomes B+i×wB + i \times w. For example, if int A[50] starts at 2000 and an int takes 4 bytes, A[17] is at 2000+17×4=20682000 + 17 \times 4 = 2068. This one multiplication is why reading A[i] takes Θ(1)\Theta(1) 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 B+[(i−lr)×N+(j−lc)]×wB + [(i - \mathit{lr}) \times N + (j - \mathit{lc})] \times w, because (i−lr)(i - \mathit{lr}) full rows of N elements come before row i.
  • In column-major order the address is B+[(j−lc)×M+(i−lr)]×wB + [(j - \mathit{lc}) \times M + (i - \mathit{lr})] \times w, because (j−lc)(j - \mathit{lc}) full columns of M elements come first.

Worked example. Let A[1..10][1..15] be stored from base address 1000 with w=4w = 4 bytes, and find the address of A[4][7]. Here M=10M = 10 and N=15N = 15. In row-major order, (4−1)×15+(7−1)=51(4 - 1) \times 15 + (7 - 1) = 51 elements come before it, so the address is 1000+51×4=12041000 + 51 \times 4 = 1204.

In column-major order, (7−1)×10+(4−1)=63(7 - 1) \times 10 + (4 - 1) = 63 elements come first, so the address is 1000+63×4=12521000 + 63 \times 4 = 1252. 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 top=−1\mathit{top} = -1, and a stack in an array of size MAX is full when top=MAX−1\mathit{top} = \mathit{MAX} - 1.

#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 Θ(1)\Theta(1) time. Pushing onto a full stack is called overflow, and popping from an empty one is called underflow. At any moment the stack holds top+1\mathit{top} + 1 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 1n+1(2nn)\dfrac{1}{n+1}\binom{2n}{n} different orders, the Catalan number, which gives 1, 2, 5, 14 and 42 for n=1n = 1 to 55. 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:

  1. Send every operand straight to the output.
  2. Push a left bracket, and on a right bracket pop operators to the output until the matching left bracket, then discard both brackets.
  3. 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.
  4. 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 8÷28 \div 2 and not 2÷82 \div 8.

Worked example. Evaluate 6 2 3 + − 3 8 2 ÷ + *. The stack grows to 6 2 3, the + makes it 6 5, and the − gives 6−5=16 - 5 = 1. 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 6−4=26 - 4 = 2.

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 Θ(n)\Theta(n) 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 Θ(1)\Theta(1) 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 N−1N - 1 is followed by index 0. Every move becomes rear=(rear+1) mod N\mathit{rear} = (\mathit{rear} + 1) \bmod N or front=(front+1) mod N\mathit{front} = (\mathit{front} + 1) \bmod N. 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 front=rear\mathit{front} = \mathit{rear} could mean either empty or full. The usual answer is to leave one cell always unused. Then the queue is empty when front=rear\mathit{front} = \mathit{rear} and full when (rear+1) mod N=front(\mathit{rear} + 1) \bmod N = \mathit{front}, so an array of size N holds at most N−1N - 1 elements. The other answer is to keep a separate count, which lets all N cells be used.

Worked example. Take N=5N = 5 with front=rear=0\mathit{front} = \mathit{rear} = 0. Enqueue 10, 20, 30 and 40: they fill cells 0 to 3, rear becomes 4, and (4+1) mod 5=0=front(4 + 1) \bmod 5 = 0 = \mathit{front}, so the queue is full with 4 elements. Dequeue twice, so front=2\mathit{front} = 2; then enqueue 50 into cell 4 and 60 into cell 0, and rear becomes 1, which is full again because (1+1) mod 5=2=front(1 + 1) \bmod 5 = 2 = \mathit{front}.

The number of elements at any moment is (rear−front+N) mod N(\mathit{rear} - \mathit{front} + N) \bmod N. In the last state that gives (1−2+5) mod 5=4(1 - 2 + 5) \bmod 5 = 4, 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 Θ(1)\Theta(1) Θ(n)\Theta(n)
Sorted array or list Θ(n)\Theta(n) Θ(1)\Theta(1)
Binary heap Θ(log⁡n)\Theta(\log n) Θ(log⁡n)\Theta(\log n)

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, S1S_1 for input and S2S_2 for output:

  • To enqueue x, push x onto S1S_1.
  • To dequeue, first check S2S_2, and if it is empty, pop every element of S1S_1 and push it onto S2S_2; then pop S2S_2.

Moving the elements reverses their order, so the oldest element ends on top of S2S_2. A single dequeue can cost Θ(n)\Theta(n) 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 4n4n stack operations, which is amortised Θ(1)\Theta(1) 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 S1S_1 into S2S_2 so that 1 is on top, and returns 1. The value 4 goes to S1S_1, the next two dequeues pop 2 and 3 from S2S_2, 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:

  1. They ask you to define the stack and queue ADTs and write their array implementations in C, with overflow and underflow checks.
  2. They ask you to convert an infix expression to postfix or prefix and to evaluate a postfix expression, showing the stack at each step.
  3. They ask you to explain why a circular queue is needed and to state its full and empty conditions.
  4. 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).

  1. Write C functions for push and pop on an array stack, and explain overflow and underflow with an example. (10 marks)
  2. Convert (A + B) * C − D ÷ (E + F) to postfix and to prefix, showing the operator stack at each step. (10 marks)
  3. 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 S1S_1 receiving new elements and S2S_2 giving out old ones.
  • Write enqueue as a single push onto S1S_1, which takes constant time.
  • Write dequeue as a pop from S2S_2, where all of S1S_1 is first moved into S2S_2 only when S2S_2 is empty.
  • Show with a short example that the oldest element always reaches the top of S2S_2.
  • Argue that each element is pushed twice and popped twice in its life, so n operations cost at most 4n4n stack steps and the amortised cost is Θ(1)\Theta(1).
  • Conclude that a single dequeue can still take Θ(n)\Theta(n) in the worst case, and say where such a design is useful.

Quick revision

  • An array gives Θ(1)\Theta(1) access because the address of A[i] is B+(i−L)×wB + (i - L) \times w.
  • Row-major uses the number of columns, B+[(i−lr)×N+(j−lc)]×wB + [(i - \mathit{lr}) \times N + (j - \mathit{lc})] \times w, and C uses row-major order.
  • Column-major uses the number of rows, B+[(j−lc)×M+(i−lr)]×wB + [(j - \mathit{lc}) \times M + (i - \mathit{lr})] \times w.
  • A stack is LIFO, and with top = −1 for empty it is full at top=MAX−1\mathit{top} = \mathit{MAX} - 1.
  • 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 Θ(n)\Theta(n) stack space.
  • A circular queue is empty when front=rear\mathit{front} = \mathit{rear} and full when (rear+1) mod N=front(\mathit{rear} + 1) \bmod N = \mathit{front}, holding N−1N - 1 elements.
  • A priority queue on a binary heap gives Θ(log⁡n)\Theta(\log n) insert and delete.
  • A queue from two stacks costs amortised Θ(1)\Theta(1) per operation, though one dequeue can cost Θ(n)\Theta(n).
  • Inputs 1 to n pushed in order give a Catalan number of outputs, 5 for n=3n = 3, and 3 1 2 is impossible.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. `int A[50]` starts at address 2000 and an int takes 4 bytes. The address of `A[17]` is:

  2. `A[1..10][1..15]` is stored in row-major order from address 1000 with 4-byte elements. The address of `A[4][7]` is:

  3. For the same array stored in column-major order, the address of `A[4][7]` is:

  4. In an array stack of size MAX with top=−1\mathit{top} = -1 for empty, the stack is full when:

  5. The postfix form of `A + B * C − D ÷ E` is:

  6. With ↑ as a right-associative power operator, the postfix form of `A ↑ B ↑ C` is:

  7. The value of the postfix expression `6 2 3 + − 3 8 2 ÷ + *` is:

  8. The value of the prefix expression `− * 2 3 4` is:

  9. `void f(int n){ if(n==0) return; printf("%d ",n); f(n−1); printf("%d ",n); }` What does f(3) print?

  10. In a queue, deletion takes place at the:

  11. A circular queue uses an array of size NN with one cell always left empty. It is full when:

  12. With N=5N = 5, front=2\mathit{front} = 2 and rear=1\mathit{rear} = 1 in such a circular queue, the number of elements is:

  13. A priority queue is built on a binary heap of n elements. Insert and delete-min take:

  14. A queue is built from two stacks, moving S1S_1 into S2S_2 only when S2S_2 is empty. The amortised cost per operation over n operations is:

  15. 1, 2, 3 are pushed in this order, with pops allowed at any time. Which output is NOT possible?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

How is the address of A[i][j] found in row-major order?

Count the full rows before row i and the elements before column j: B + [(i − lr) × N + (j − lc)] × w, where N is the number of columns.

What is the postfix form of A + B * C?

It is A B C * +, because multiplication has higher precedence and is applied before the addition.

How many elements can a circular queue of size N hold?

With one cell always left empty it holds N − 1 elements; with a separate count it can hold all N.

Can a queue be built from two stacks?

Yes. Push new items on one stack and pop from the other, refilling it only when empty; each operation costs amortised Θ(1).

More in this module: Data structures

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): arrays, stacks, queues and recursion