Data Structures and Algorithms: Stack, Queue, Trees, Big-O and MCQs
A data structure is a way of organising data in memory so that it can be used efficiently, and an algorithm is the step-by-step method that works on it. Papers for lecturer computer science, programmer, IT officer and bank IT posts test whether you know that a stack is LIFO and a queue is FIFO, can trace a series of push and pop operations, and remember the time complexity of binary search or merge sort. Most questions are quick once the core rules are clear.
Asked in: PPSC, FPSC, NTS, ETEA, KPPSC, SSC, IBPS and ICS/ECAT computer
Classifying data structures
Primitive data types such as integer, float, character and Boolean hold single values. Non-primitive data structures are built from them and are divided into linear and non-linear structures.
In a linear structure the elements form a sequence, each having at most one predecessor and one successor: arrays, stacks, queues and linked lists. In a non-linear structure an element can be connected to several others, forming a hierarchy or network: trees and graphs.
A static structure has a fixed size decided in advance, as with an ordinary array. A dynamic structure can grow and shrink while the program runs, as with a linked list. The basic operations on any structure are traversal (visiting every element), insertion, deletion, searching and sorting.
- Linear: array, stack, queue, linked list
- Non-linear: tree, graph
- Static: fixed size (array); Dynamic: grows and shrinks (linked list)
- Operations: traverse, insert, delete, search, sort
Arrays
An array stores elements of the same data type in contiguous (adjacent) memory locations, each identified by an index. In C, C++, Java and Python indexing starts at 0, so an array of 10 elements has indices 0 to 9.
Because elements sit side by side, the address of any element can be calculated directly, which gives random access in constant time, O(1): address of A[i] = base address + i × size of one element. Inserting or deleting in the middle is slow, O(n), because later elements must be shifted.
A two-dimensional array stores a table of rows and columns. A 2D array with 3 rows and 4 columns holds 3 × 4 = 12 elements. Most languages store it in row-major order, one complete row after another.
- Same data type, contiguous memory, index from 0
- Address of A[i] = base + i × element size (0-based)
- Access by index: O(1); insert/delete in middle: O(n)
- 2D array elements = rows × columns
Stacks
A stack is a linear structure in which insertion and deletion happen at one end only, called the top. It follows LIFO, Last In First Out, like a pile of plates: the plate placed last is taken first.
PUSH adds an element on top, POP removes the top element and PEEK (TOP) reads it without removing it. Pushing onto a full stack causes overflow; popping from an empty stack causes underflow.
Stacks are used for function calls and recursion (the call stack), undo in editors, the back button of a browser, checking balanced brackets, reversing a word, converting infix expressions to postfix, and evaluating postfix expressions. In postfix (reverse Polish) notation the operator comes after its operands: infix A + B × C becomes A B C × +. To evaluate postfix, push numbers; when an operator appears, pop two numbers, apply it and push the result.
- Stack: LIFO, one end (top)
- PUSH: add on top; POP: remove top; PEEK: read top
- Overflow: push on full; Underflow: pop on empty
- Infix A + B × C → Postfix A B C × +
- Uses: recursion, undo, browser back, bracket matching
Queues and linked lists
A queue is a linear structure that follows FIFO, First In First Out, like people waiting at a bank counter. Elements are added at the rear (ENQUEUE) and removed from the front (DEQUEUE). Queues are used for printer spooling, CPU scheduling, handling requests on a server and breadth-first search.
A circular queue joins the last position back to the first so that space freed at the front can be reused. A priority queue serves elements by priority rather than arrival order. A deque (double-ended queue) allows insertion and deletion at both ends.
A linked list is a chain of nodes. In a singly linked list each node holds data and a pointer (address) to the next node; the first node is reached through a pointer called head, and the last node's pointer is NULL. A doubly linked list node also points to the previous node, and in a circular linked list the last node points back to the first. Linked lists grow easily and insert or delete quickly once the position is known, but they have no random access: reaching the k-th node means following k links, O(n).
- Queue: FIFO; insert at rear, delete from front
- Circular queue reuses space; Priority queue serves by priority
- Deque: insert/delete at both ends
- Singly linked node = data + pointer to next; last pointer = NULL
- Doubly linked node = previous + data + next
Trees and graphs
A tree is a hierarchical, non-linear structure. The top node is the root; a node directly below another is its child, and the one above is its parent; a node with no children is a leaf. The height of a tree is the length of the longest path from the root to a leaf. A tree with n nodes always has exactly n − 1 edges.
In a binary tree each node has at most two children, left and right; level 0 can hold 1 node, level 1 up to 2, level 2 up to 4, doubling at each level. In a binary search tree (BST) every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. Traversals: preorder visits Root, Left, Right; inorder visits Left, Root, Right; postorder visits Left, Right, Root. Inorder traversal of a BST lists the values in ascending order.
A graph is a set of vertices (nodes) joined by edges. In an undirected graph edges have no direction; in a directed graph (digraph) they do; in a weighted graph each edge carries a value such as distance. Graphs model road maps, computer networks and social networks. Breadth-first search (BFS) explores level by level using a queue; depth-first search (DFS) goes as deep as possible first using a stack (or recursion).
- Tree with n nodes has n − 1 edges
- Binary tree: at most 2 children per node
- BST: left subtree smaller, right subtree larger
- Preorder: Root-Left-Right; Inorder: Left-Root-Right; Postorder: Left-Right-Root
- Inorder of BST = ascending order
- BFS uses a queue; DFS uses a stack
Searching, sorting and Big-O
Big-O notation describes how the running time (or memory) of an algorithm grows as the input size n grows, usually for the worst case. From slowest-growing to fastest-growing, common classes are O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n), O(n²) quadratic and O(2ⁿ) exponential.
Linear (sequential) search checks elements one by one and works on any list; its worst case is O(n). Binary search works only on a sorted list: it compares the target with the middle element and discards half the list each time, so its worst case is O(log n). For 1,000 sorted items it needs at most 10 comparisons, because halving 1,000 repeatedly reaches 1 within 10 steps.
Bubble sort repeatedly swaps neighbouring elements that are out of order, so after each pass the largest remaining element bubbles to the end. Selection sort repeatedly selects the smallest remaining element and puts it in place. Insertion sort builds a sorted part by inserting each new element where it belongs. All three are O(n²) in the worst case. Merge sort divides the list into halves, sorts them and merges them, and is O(n log n) in every case. Quick sort partitions around a pivot and is O(n log n) on average but O(n²) in the worst case. Heap sort is O(n log n).
- Growth order: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ)
- Linear search: O(n); Binary search: O(log n), needs sorted data
- Bubble, selection, insertion sort: O(n²) worst case
- Merge sort: O(n log n) all cases; Heap sort: O(n log n)
- Quick sort: O(n log n) average, O(n²) worst
Solved examples
- Starting with an empty stack, perform: PUSH 5, PUSH 8, POP, PUSH 3, PUSH 9, POP, POP. Which values are popped, in order, and what is left?
- PUSH 5, PUSH 8: stack (bottom to top) is 5, 8. POP removes 8.
- PUSH 3, PUSH 9: stack is 5, 3, 9. POP removes 9, then POP removes 3.
- Only 5 remains. Each POP took the most recently pushed value still present (LIFO).
Answer: Popped 8, 9, 3; stack holds 5 - Starting with an empty queue, perform: ENQUEUE A, ENQUEUE B, ENQUEUE C, DEQUEUE, ENQUEUE D, DEQUEUE. What are the front and rear now?
- After three enqueues the queue (front to rear) is A, B, C. DEQUEUE removes A from the front.
- ENQUEUE D adds at the rear: B, C, D. DEQUEUE removes B.
- The queue is C, D, so C is at the front and D at the rear (FIFO).
Answer: Front C, rear D - Use binary search to find 25 in the sorted array 3, 8, 12, 17, 25, 31, 40 (indices 0 to 6). How many comparisons are needed?
- Low 0, high 6, middle 3 holds 17. 25 is larger, so search indices 4 to 6.
- Middle of 4 and 6 is 5, holding 31. 25 is smaller, so search index 4 only.
- Index 4 holds 25: found. A linear search would have needed 5 comparisons.
Answer: 3 comparisons (found at index 4) - Evaluate the postfix expression 6 2 3 + × using a stack.
- Push 6, push 2, push 3. The stack is 6, 2, 3.
- + pops 3 and 2 and pushes 2 + 3 = 5. The stack is 6, 5.
- × pops 5 and 6 and pushes 6 × 5 = 30. In infix the expression is 6 × (2 + 3).
Answer: 30 - Insert 50, 30, 70, 20, 40 in that order into an empty binary search tree. Give the inorder and preorder traversals.
- 50 is the root. 30 is smaller, so it goes left; 70 is larger, so it goes right. 20 is less than 50 and less than 30, so it is the left child of 30; 40 is less than 50 but more than 30, so it is the right child of 30.
- Inorder (Left, Root, Right): 20, 30, 40, 50, 70, which is sorted, as always for a BST.
- Preorder (Root, Left, Right): 50, 30, 20, 40, 70.
Answer: Inorder 20 30 40 50 70; Preorder 50 30 20 40 70 - An integer array A starts at memory address 1000 and each integer takes 4 bytes. Indexing starts at 0. What is the address of A[6]?
- Address of A[i] = base + i × size.
- A[6] = 1000 + 6 × 4 = 1000 + 24.
- A[6] is the seventh element; the six before it occupy 24 bytes.
Answer: 1024
Exam shortcuts
- Stack = LIFO = plates; Queue = FIFO = bank line. Stack works at one end, a queue at two.
- When tracing, write the structure after every operation, marking the top of a stack or the front and rear of a queue.
- Binary search needs sorted data and halves the list each step: about log₂ n comparisons, so 1,000 items need at most 10 and 1,000,000 at most 20.
- Only merge sort and heap sort are O(n log n) even in the worst case; quick sort's worst case is O(n²).
- BFS pairs with a queue, DFS with a stack; inorder traversal of a BST gives sorted output.
Common mistakes
- Popping from the bottom of a stack. POP always removes the most recently pushed element still present.
- Applying binary search to an unsorted list. It only works when the data is sorted.
- Saying a tree with n nodes has n edges. Every node except the root has exactly one edge to its parent, so there are n − 1 edges.
- Forgetting that arrays usually start at index 0, which puts A[6] at the seventh position, base + 6 × size.
Practice MCQs
- Which data structure works on the Last In, First Out (LIFO) principle?
A) Queue
B) Stack
C) Linked list
D) Graph
Answer: B) Stack — In a stack, the element pushed last is the first to be popped. A queue is First In, First Out, while a linked list and a graph do not impose a fixed insertion and removal order. - What condition must a list satisfy before binary search can be used on it?
A) It must have an even number of items
B) It must be stored as a linked list
C) It must contain no repeated values
D) It must be sorted
Answer: D) It must be sorted — Binary search decides which half to discard by comparing with the middle element, which only works if the list is sorted. The number of items can be odd or even, it works best on arrays rather than linked lists, and repeated values do not stop it from working. - What is the worst-case time complexity of linear search on n items?
A) O(n)
B) O(log n)
C) O(1)
D) O(n²)
Answer: A) O(n) — In the worst case the item is last or absent, so all n elements are checked: O(n). O(log n) belongs to binary search, O(1) would mean a fixed number of steps whatever the size, and O(n²) is typical of simple sorting algorithms. - Which of the following is a non-linear data structure?
A) Array
B) Queue
C) Tree
D) Stack
Answer: C) Tree — A tree is hierarchical: one node can have several children, so its elements do not form a single sequence. Arrays, queues and stacks are linear because each element has at most one before it and one after it. - In a singly linked list, each node stores its data and:
A) An index into an array
B) The address of the previous node only
C) The total size of the list
D) The address of the next node
Answer: D) The address of the next node — A singly linked list node has a data part and a pointer to the next node, with NULL in the last node. A pointer to the previous node is added only in a doubly linked list, and nodes do not hold array indices or the size of the list. - Starting with an empty stack: PUSH 4, PUSH 7, POP, PUSH 2, PUSH 6, POP. Which element is now on top?
A) 4
B) 2
C) 7
D) 6
Answer: B) 2 — After PUSH 4 and PUSH 7, POP removes 7, leaving 4. PUSH 2 and PUSH 6 give 4, 2, 6, and POP removes 6, so 2 is on top. Both 7 and 6 have been popped, and 4 is at the bottom. - Starting with an empty queue: ENQUEUE 10, ENQUEUE 20, ENQUEUE 30, DEQUEUE, ENQUEUE 40, DEQUEUE. Which element is now at the front?
A) 20
B) 40
C) 30
D) 10
Answer: C) 30 — The first DEQUEUE removes 10, leaving 20, 30; ENQUEUE 40 gives 20, 30, 40; the second DEQUEUE removes 20, so 30 is at the front. 10 and 20 have already left the queue, and 40 is at the rear. - What is the worst-case time complexity of merge sort?
A) O(n log n)
B) O(n²)
C) O(n)
D) O(log n)
Answer: A) O(n log n) — Merge sort splits the list into halves about log n times and does O(n) merging work at each level, so it is O(n log n) in every case. O(n²) is the worst case of bubble, selection, insertion and quick sort; no comparison sort can be O(n) or O(log n) in the worst case. - Breadth-first search (BFS) of a graph is normally implemented with a:
A) Stack
B) Hash table
C) Binary search tree
D) Queue
Answer: D) Queue — BFS visits vertices level by level, and a FIFO queue keeps them in the order they were discovered. A stack gives depth-first search instead, while a hash table or a binary search tree is not what drives the order of a BFS. - How many edges does a tree with 15 nodes have?
A) 15
B) 14
C) 16
D) 30
Answer: B) 14 — Every node except the root is joined to its parent by exactly one edge, so a tree with n nodes has n − 1 edges: 15 − 1 = 14. Fifteen or more edges would create a cycle, and a tree has none. - An inorder traversal of a binary search tree lists its values in:
A) Ascending order
B) Descending order
C) Order of insertion
D) Level-by-level order
Answer: A) Ascending order — Inorder visits the left subtree, then the node, then the right subtree; in a BST the left side is smaller and the right side larger, so values come out in ascending order. Descending order would need Right, Root, Left, insertion order is not preserved, and level-by-level order is breadth-first traversal. - What is the value of the postfix expression 5 3 2 × + ?
A) 16
B) 25
C) 11
D) 13
Answer: C) 11 — Push 5, 3 and 2; × pops 2 and 3 and pushes 6; + pops 6 and 5 and pushes 11. The value 16 comes from wrongly computing (5 + 3) × 2, 13 from 5 × 2 + 3, and 25 does not follow from any order of these operations. - What is the maximum number of comparisons binary search needs to find an item in a sorted array of 1,000 elements?
A) 500
B) 10
C) 100
D) 1,000
Answer: B) 10 — Each comparison halves the remaining range, and 2¹⁰ = 1,024, which covers 1,000 items, so at most 10 comparisons are needed. 1,000 is the worst case of linear search, and 500 and 100 are far more than binary search ever needs. - Array A starts at address 2000, each element takes 2 bytes and indexing starts at 0. What is the address of A[15]?
A) 2015
B) 2032
C) 2028
D) 2030
Answer: D) 2030 — Address = base + index × size = 2000 + 15 × 2 = 2030. 2015 ignores the element size, 2028 is the result if indexing began at 1 (2000 + 14 × 2), and 2032 counts one element too many. - Bubble sort is applied to 5, 1, 4, 2, 8 to put it in ascending order. What is the list after the first complete pass?
A) 1, 4, 2, 5, 8
B) 1, 2, 4, 5, 8
C) 1, 5, 4, 2, 8
D) 1, 4, 5, 2, 8
Answer: A) 1, 4, 2, 5, 8 — Compare neighbours left to right: 5 and 1 swap, 5 and 4 swap, 5 and 2 swap, 5 and 8 stay, giving 1, 4, 2, 5, 8. The fully sorted list needs a second pass, while the other two lists stop partway through the first pass.
Questions
What is the difference between a stack and a queue?
A stack is LIFO: insertion and deletion happen at the same end, the top. A queue is FIFO: elements enter at the rear and leave from the front, so the earliest added leaves first.
Why is binary search faster than linear search?
Binary search halves the sorted list at every step, so its worst case is O(log n), about 20 comparisons for a million items. Linear search may have to check every item, O(n).
Which sorting algorithm is fastest?
For large lists, merge sort and heap sort guarantee O(n log n), and quick sort is usually fastest in practice with O(n log n) on average, though its worst case is O(n²). Bubble, selection and insertion sort are O(n²).
Is a linked list better than an array?
It depends on the use. Arrays give O(1) access by index but slow insertion in the middle; linked lists grow freely and insert quickly at a known position but need O(n) to reach an element.