Top Banner Ad
BCS301 · 2024-2522 Questions

DATA STRUCTURE — 2024-25

Section A

2 Marks Each · 7 questions
Q1a2MUnit 1 — Linked lists: Array Implementation and Pointer Implementation of Singly Linked Lists
Core Concept

Explain why do we need a pointer to maintain a linked list structure?

A pointer is needed because linked list nodes are not stored in consecutive memory, so the address of the next node cannot be computed from the current address. The pointer records that address explicitly and a null pointer marks the end of the list, allowing traversal from the head.

Key Points

  • Nodes are non contiguous
  • Pointer stores next address
  • Null marks the end
Q1b2MUnit 1 — Single and Multidimensional Arrays
Survival ModePredicted

If an array starts at address 2000 and each integer takes 4 bytes, evaluate the address of arr[5]arr[5].

For an array starting at base address 2000 with four bytes per integer, the address of index five is the base plus five times four, which is 2020 if indexing begins at zero. If indexing begins at one, the offset is four times four, giving 2016. State the indexing convention before applying the formula.

Key Points

  • Address is base plus offset times size
  • Zero based gives 2020
  • One based gives 2016
Q1c2MUnit 2 — Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues
Core Concept

Explain Priority Queue and its significance?

A priority queue removes the element with the highest priority rather than the oldest element. Each item carries a priority value, and deletion returns the maximum or minimum according to convention. It is significant in scheduling, event simulation and Dijkstra's algorithm, and is usually implemented with a heap for efficient insertion and deletion.

Key Points

  • Removes highest priority
  • Not first in first out
  • Used in scheduling and Dijkstra
Q1d2MUnit 2 — Primitive Stack operations: Push & Pop
Core Concept

The following sequence of operations is performed on stack: PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, POP, PUSH (20), POP. Demonstrate the sequence of the values popped out.

Push ten gives stack ten. Push twenty gives ten, twenty with twenty on top. Pop returns twenty, leaving ten. Push ten then twenty gives ten, ten, twenty. Pop returns twenty and the next pop returns ten, leaving ten. Push twenty then pop returns twenty. The popped values in order are twenty, twenty, ten, twenty.

Key Points

  • Track stack after each operation
  • First pop returns 20
  • Sequence 20, 20, 10, 20
Q1e2MUnit 3 — Index Sequential Search
Core Concept

Illustrate the concept of Indexed Sequential search.

Indexed sequential search uses an index table that stores the largest key or starting key of each block of a sorted file. The index is searched first to identify the block containing the target, and then only that block is searched sequentially. It reduces the number of comparisons compared with scanning the entire file and is useful for large sorted files on disk.

Key Points

  • Index gives block boundaries
  • Search index then one block
  • Fewer comparisons than full scan
Q1f2MUnit 4 — Basic terminology used with Tree
Survival ModePredicted

Explain the concept of NonLinear data structures with the help of example.

Nonlinear data structures arrange elements so that one element may be connected to several others rather than forming a single sequence. Trees are hierarchical with a root and parent child relationships, as in a binary search tree or file system. Graphs are networks of vertices and edges, as in road maps or social connections. They model relationships that linear lists cannot express naturally.

Key Points

  • Not a single sequence
  • Trees are hierarchical
  • Graphs are networks
Q1g2MUnit 4 — Threaded Binary trees
Core Concept

Illustrate the significance of Threaded Binary Tree.

A threaded binary tree replaces null child pointers with threads to the inorder predecessor or successor. This allows inorder traversal without recursion or an auxiliary stack, since the next node can be found directly. It saves stack space and speeds repeated traversals, but insertion and deletion become more complex because threads must be maintained.

Key Points

  • Threads replace null pointers
  • Inorder needs no stack
  • Updates are more complex

Section B

7 Marks Each · 5 questions
Q2a7MUnit 1 — Representation of Arrays: Row Major Order
Predicted

An array ARR[−5,15,10,20]ARR[-5, 15, 10, 20] stores elements in Row Major Wise with each element requiring 2 bytes of storage. Evaluate the address of ARR[10][15]ARR[10][15] when the base address is 2500.

1. Interpret the bounds: ARR[−5,15,10,20]ARR[-5,15,10,20] means row indices −5…15-5 \ldots 15 and column indices 10…2010 \ldots 20.

  • Rows: 15−(−5)+1=2115-(-5)+1 = 21; columns (used in row-major formula): 20−10+1=1120-10+1 = 11.
  • Element size = 2 bytes, base address = 2500.

2. Row-major formula: Address(i,j)=Base+[(i−Lr)×Nc+(j−Lc)]×sizeAddress(i,j) = Base + [(i-L_r)\times N_c + (j-L_c)]\times size where Lr=−5L_r=-5, Lc=10L_c=10, Nc=11N_c=11.

3. Substitute i=10i=10, j=15j=15:

  • Row offset: 10−(−5)=1510-(-5) = 15 complete rows -> 15×11=16515\times11 = 165 elements.
  • Column offset: 15−10=515-10 = 5 elements.
  • Total offset = 165+5=170165+5 = 170 elements = 170×2=340170\times2 = 340 bytes.
  • Address=2500+340=2840Address = 2500 + 340 = 2840.

Finding an element's address. A multidimensional array is stored in linear memory, so a mapping from subscripts to a single address is needed. In row major order the last subscript varies fastest, meaning all elements of a row occupy consecutive locations. In column major order the first subscript varies fastest, meaning all elements of a column are consecutive. For an array declared with lower and upper bounds, the length of a dimension is the upper bound minus the lower bound plus one. The address of an element is the base address plus the offset in elements multiplied by the size of one element. For a two dimensional array with m rows and n columns indexed from zero, the row major address of element i j is base plus the size times i times n plus j, and the column major address is base plus the size times j times m plus i. When indices start at a nonzero lower bound, subtract the lower bound from each subscript before applying the formula. For an array with negative bounds the same subtraction applies, so an index of minus five maps to offset zero. For a three dimensional array the row major offset is the first index group times the product of the other two dimension lengths, plus the second group times the last dimension length, plus the third group. A good answer lists the dimension lengths and total count, writes the general formula for each order, substitutes the given bounds and subscripts carefully and reports the address in bytes. Showing the intermediate offset is clearer than quoting a final number and makes it easy to check the result. Mentioning that the choice of order affects which operations are cache friendly links the formula to practical performance.

Result: The address of ARR[10][15]ARR[10][15] in row-major order is 2840.

ARR[−5,15,10,20]ARR[-5,15,10,20] −5…15-5 \ldots 15 10…2010 \ldots 20
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Bounds: rows -5..15 (21 rows), columns 10..20 (11 columns), element size 2 bytes
  • Row-major: Address = Base + ((i - Lr) * columns + (j - Lc)) * size
  • (10+5)*11 + (15-10) = 170 elements = 340 bytes
  • Address of ARR[10][15] = 2500 + 340 = 2840
Q2b7MUnit 2 — Array and Linked Implementation of Stack in C
Core Concept

If a stack is implemented using Linked List, then show the logical representation of nodes as a stack. Illustrate PUSH and POP operations of this type of stack.

Answer: A linked stack is a chain of nodes; the head pointer top is the stack top. Each node is data | next, and the last node's next = NULL. Logical representation (stack grows toward the left):

top ---> [ 30 | * ] ---> [ 20 | * ] ---> [ 10 | NULL ]
           newest                      oldest (bottom)

PUSH(40): allocate node, set new->next = top, then top = new:

top ---> [ 40 | * ] ---> [ 30 | * ] ---> [ 20 | * ] ---> [ 10 | NULL ]

POP: read top->data, save p = top, set top = top->next, free p. POP returns 40 and the stack returns to the previous picture. A POP on top NULL is underflow.

A last in first out structure. A stack is a linear data structure in which insertion and deletion occur at the same end, called the top. The last element inserted is the first removed, which is why it is described as last in first out. The basic operations are push, which inserts an element, pop, which removes the top element, peek or top, which reads it without removing it, and tests for empty and full conditions. An array implementation uses a fixed size array and an integer top index, so push increments the index and pop decrements it, with checks for overflow and underflow. A linked implementation uses nodes whose next pointer points toward the earlier element, with the head of the list acting as the top; push inserts at the head and pop removes the head, so no shifting is needed and the stack grows dynamically. For the given sequence of operations, pushing ten then twenty makes twenty the top, so the first pop returns twenty. Pushing ten and twenty again and popping twice returns twenty then ten, leaving ten in the stack. A final push of twenty followed by a pop returns twenty, and the sequence of popped values is twenty, twenty, ten, twenty. A good answer shows the stack contents after each operation in a table, states the array and linked representations with their overflow behaviour and explains where stacks are used, such as expression evaluation, function calls, undo operations and depth first search. Mentioning that the top pointer is the only access point is the key to understanding both implementations.

Result: The linked representation needs no contiguous memory; PUSH and POP are only pointer updates at the head, so both are O(1).

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Linked stack: top pointer to head node; each node is data + next, last next = NULL
  • PUSH: allocate node, new->next = top, top = new (O(1))
  • POP: read top data, advance top to top->next, free old node; underflow if NULL
  • Example [30|]->[20|]->[10|NULL]; PUSH(40) puts 40 at the head
Q2c7MUnit 4 — Binary Search Tree
Survival ModePredictedRepeated

Construct a binary tree with the following traversals: Inorder: B C A E G D H F I J.

Answer: A Binary Search Tree is a binary tree in which, for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger than the node's key. Search, insert and delete take O(h)O(h) time, where h is the tree height (O(log n) if balanced). Inserting 10, 12, 5, 4, 20, 8, 7, 15, 13: 10 becomes root; 12 goes right; 5, 4 go left of 10; 8 goes right of 5; 7 goes left of 8; 20 goes right of 12; 15 goes left of 20; 13 goes right of 15.

            10
          /    \
         5      12
        / \       \
       4   8       20
          /        /
         7       15
                /
              13

Inorder traversal: 4, 5, 7, 8, 10, 12, 13, 15, 20 (always sorted).

Hierarchical data structures. A tree is a nonlinear structure consisting of nodes connected by edges, with one root node and a parent child relationship. Important terms include root, parent, child, sibling, leaf, internal node, degree, level, height and depth. A binary tree has at most two children per node, and a binary search tree adds the rule that values in the left subtree are smaller than the node and values in the right subtree are larger, so insertion and search take time proportional to the height. Inserting the given sequence into a binary search tree places each new value by comparing with the root and descending until an empty child is found. An AVL tree is a self balancing binary search tree in which the heights of the left and right subtrees of every node differ by at most one. After an insertion, the balance factor of ancestors is updated and the first unbalanced node is repaired by a single or double rotation depending on whether the insertion was into the outer or inner side. A complete binary tree fills every level except possibly the last, with nodes as far left as possible, which makes it ideal for array based heap storage. An extended binary tree adds external null nodes to make every internal node have exactly two children, and this device leads to the relation between external and internal path lengths. Huffman coding uses a binary tree in which more frequent characters are placed nearer the root, so their code words are shorter; the tree is built by repeatedly combining the two lowest probabilities until one root remains, and the average code length is the sum of probability times code length. A good answer defines the terms, draws the requested trees or gives the insertion sequence with rotations, states the path length proof by induction on the number of internal nodes, and explains the Huffman construction with the computed average length. Mentioning that balancing keeps height logarithmic and therefore keeps search efficient is the key idea linking the topics.

Result: The constructed BST has root 10 as shown; its inorder sequence is the sorted input keys.

O(h)O(h)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
10 512 4820 715 left subtree smaller, right subtree larger at every node

Key Points

  • BST property: left subtree keys < node key < right subtree keys
  • Insertion walk: compare with node and go left or right until an empty child is found
  • Resulting tree: 10 root; left 5 (4, 8 with 7); right 12 (20 with 15 and 13)
  • Inorder traversal gives sorted order 4, 5, 7, 8, 10, 12, 13, 15, 20
Q2d7MUnit 4 — Concept & Basic Operations for AVL Tree
Survival ModePredictedRepeated

Construct an AVL Tree by inserting following sequence of elements, starting with an empty tree: 5,1,91,50,60,30,40,80,55.

Answer: An AVL tree keeps the balance factor bf=height(left)−height(right)bf = height(left) - height(right) in {-1,0,1}. Insert as in a BST, update heights upward, and rebalance the first unbalanced ancestor: LL -> right rotation, RR -> left rotation, LR -> left rotation on the child then right on the ancestor, RL -> right on the child then left on the ancestor. Rotations during the given sequence: after 60 an RR case at 71; after 30 an LL case at 41; after 40 an LR case at 41; after 55 an RR case at 50. No rotation is needed for 80. Final AVL tree (inorder 30, 40, 41, 50, 55, 56, 60, 71, 80, 91):

                56
              /    \
            40      71
           /  \    /  \
         30   50  60   91
              / \      /
            41  55    80

Height = 4; every node has |bf| <= 1.

Hierarchical data structures. A tree is a nonlinear structure consisting of nodes connected by edges, with one root node and a parent child relationship. Important terms include root, parent, child, sibling, leaf, internal node, degree, level, height and depth. A binary tree has at most two children per node, and a binary search tree adds the rule that values in the left subtree are smaller than the node and values in the right subtree are larger, so insertion and search take time proportional to the height. Inserting the given sequence into a binary search tree places each new value by comparing with the root and descending until an empty child is found. An AVL tree is a self balancing binary search tree in which the heights of the left and right subtrees of every node differ by at most one. After an insertion, the balance factor of ancestors is updated and the first unbalanced node is repaired by a single or double rotation depending on whether the insertion was into the outer or inner side. A complete binary tree fills every level except possibly the last, with nodes as far left as possible, which makes it ideal for array based heap storage. An extended binary tree adds external null nodes to make every internal node have exactly two children, and this device leads to the relation between external and internal path lengths. Huffman coding uses a binary tree in which more frequent characters are placed nearer the root, so their code words are shorter; the tree is built by repeatedly combining the two lowest probabilities until one root remains, and the average code length is the sum of probability times code length. A good answer defines the terms, draws the requested trees or gives the insertion sequence with rotations, states the path length proof by induction on the number of internal nodes, and explains the Huffman construction with the computed average length. Mentioning that balancing keeps height logarithmic and therefore keeps search efficient is the key idea linking the topics.

Result: After the ten insertions the balanced tree has root 56 with the structure shown; four rotations (RR, LL, LR, RR) restore the AVL property.

bf=height(left)−height(right)bf = height(left) - height(right)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
AVL tree after all insertions 56 4180 30506091 balance factors stay within plus or minus one using LL, RR, LR and RL rotations

Key Points

  • AVL tree: balance factor = height(left) - height(right), always -1, 0 or +1
  • Insertion sequence causes rotations: RR at 71, LL at 41, LR at 41, RR at 50
  • Final tree root 56; left 40 (30, 50 with 41 and 55); right 71 (60, 91 with 80)
  • Inorder: 30, 40, 41, 50, 55, 56, 60, 71, 80, 91; height 4
Q2e7MUnit 5 — Graph Traversal: Depth First Search and Breadth First Search
Core Concept

Explain the Depth-first Search (DFS) algorithm with the help of an example graph. Which data structure is used for DFS and BFS?

Answer: Depth-first search explores as far as possible along one branch before backtracking. Algorithm (recursive):

DFS(v):
    mark v visited; print v
    for each unvisited neighbour w of v: DFS(w)

The iterative version uses an explicit stack: push the start vertex; pop a vertex, print it, and push its unvisited neighbours. Example graph: vertices A,B,C,D,E with edges (A,B),(A,C),(B,D),(B,E),(C,E). Starting at A, DFS visits A, then B, then D (dead end), backtracks to B, visits E, backtracks to A, then visits C. DFS order: A, B, D, E, C. The same graph by BFS gives A, B, C, D, E (level by level). Properties: time O(V+E) with adjacency lists, O(V)O(V) space for visited plus the stack/recursion; DFS detects cycles, finds connected components and is used for topological sorting. Data structures: DFS uses a stack (or recursion, which uses the call stack); BFS uses a queue (FIFO).

Representing and exploring graphs. A graph consists of a set of vertices and a set of edges connecting pairs of vertices. A weighted graph assigns a numerical cost to each edge, and the degree of a vertex is the number of edges incident on it; in a directed graph this splits into indegree and outdegree. A regular graph of degree d with n vertices has n times d divided by two edges because each edge is counted at both endpoints. Graphs are represented in memory either by an adjacency matrix or by an adjacency list. An adjacency matrix is a square array where entry i j records the presence or weight of an edge, so testing an edge is constant time and indegree and outdegree are found by summing a row and a column, but it uses order n squared space and is wasteful for sparse graphs. An adjacency list stores for each vertex a list of its neighbours, using space proportional to vertices plus edges and allowing quick iteration over neighbours, but testing a specific edge takes time proportional to the degree. Depth first search explores as far as possible along one branch before backtracking, using a stack or recursion, while breadth first search explores level by level using a queue. Connected components are found by running a traversal from each unvisited vertex and collecting all vertices reached. A good answer defines the terms, compares the two representations with a table, shows how indegree and outdegree are computed from a matrix, explains the traversal data structures and gives the connected component algorithm. Noting that matrix representation is preferred for dense graphs and list representation for sparse graphs is the practical conclusion.

Result: DFS goes deep before backtracking (example order A, B, D, E, C) and needs a stack; BFS explores level by level and needs a queue.

O(V)O(V)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
ABCDE DFS uses a stack and goes deep; BFS uses a queue and explores level by level

Key Points

  • DFS explores deep along one path then backtracks; recursive or explicit stack
  • Example edges (A,B),(A,C),(B,D),(B,E),(C,E): DFS from A gives A,B,D,E,C
  • Time O(V+E) with adjacency lists; O(V) visited array plus stack
  • DFS uses a stack; BFS uses a queue

Section C

7 Marks Each · 10 questions
Q3a7MUnit 1 — Asymptotic notations: Big Oh
Predicted

Illustrate the following: (a) Asymptotic notations (b) Time-Space Tradeoff

(a) Asymptotic notations: Asymptotic notations describe the growth of an algorithm's time or space need with input size nn, ignoring constant factors. For nonnegative ff and gg:

  • O (upper bound): f(n)=O(g(n))f(n) = O(g(n)) iff there exist c>0c > 0 and n0>=0n0 >= 0 with 0<=f(n)<=cg(n)0 \lt = f(n) \lt = c g(n) for all n>=n0n >= n0. Example: 5n2+3n=O(n2)5n^2 + 3n = O(n^2).
  • Ω (lower bound): f(n)=Ω(g(n))f(n) = Ω(g(n)) iff there exist c>0c > 0 and n0>=0n0 >= 0 with 0<=cg(n)<=f(n)0 \lt = c g(n) \lt = f(n) for all n>=n0n >= n0.
  • Θ (tight bound): f(n)=Θ(g(n))f(n) = Θ(g(n)) iff there exist c1>0c1 > 0, c2>0c2 > 0 and n0>=0n0 >= 0 with 0<=c1g(n)<=f(n)<=c2g(n)0 \lt = c1 g(n) \lt = f(n) \lt = c2 g(n) for all n>=n0n >= n0, i.e. ff is both O(g)O(g) and Ω(g)Ω(g).
  • Strict forms: f=o(g)f = o(g) means f/g−>0f/g -> 0; f=ω(g)f = ω(g) means f/g−>infinityf/g -> infinity. Growth-rate order: 1<logn<n<nlogn<n2<n3<2n<n!1 \lt log n \lt n \lt n log n \lt n^2 \lt n^3 \lt 2^n \lt n!. Diagram with axes (x = input size n, y = operations T(n)):
T(n)
 ^
 |                                             n!
 |                                        _.-'
 |                                   _.-' 2^n
 |                             _.-'
 |                       _.-' n^3
 |                  _.-' n^2
 |            _____/ n log n
 |        ___/ n
 |    ___/ log n
 |___/________________________________________-> n

The curves diverge as nn grows. A Θ bound is the band between c1g(n)c1 g(n) and c2g(n)c2 g(n) that contains f(n)f(n) beyond n0n0.

(b) Time-space tradeoff: The tradeoff is the design choice where lower running time is obtained by using more memory, or lower memory is obtained by accepting more computation. It is not a law that one must grow, but a practical exchange of resources.

  • Array lookup vs linked list: An array stores elements contiguously, so address = base + i*size gives O(1)O(1) direct access with no per-element pointer storage; but resizing or inserting in the middle costs O(n)O(n). A linked list needs one extra pointer field per node (more space per item) and O(n)O(n) traversal to find the i-th item, yet insertion/deletion at a known node is O(1)O(1). Thus the array spends a fixed contiguous block to buy fast access, while the list spends pointer space and search time to buy cheap dynamic updates.
  • Hash table: Storing keys in a table of mm slots with h(k)=kmodmh(k) = k mod m gives average O(1)O(1) search, but it consumes the whole table. Chaining adds link/node space; open addressing keeps unused slots empty. A larger table (lower load factor n/mn/m) means fewer collisions and probes, so more memory buys less time. With no table at all, sequential search uses O(1)O(1) extra space but O(n)O(n) time.
  • Merge sort vs insertion sort: Merge sort runs in Θ(nlogn)Θ(n log n) time in all cases but needs Θ(n)Θ(n) auxiliary array space for merging. Insertion sort uses only Θ(1)Θ(1) extra space but takes Θ(n2)Θ(n^2) time on average and in the worst case. Memory-rich systems choose merge sort for speed; memory-tight systems may accept insertion sort to save space (its small constants help for tiny inputs).

Measuring an algorithm without counting seconds. Complexity analysis estimates how the running time or memory requirement of an algorithm grows with the size of its input, independent of machine speed and programming language. Time complexity counts the number of basic operations as a function of input size, while space complexity counts the memory used. Asymptotic notation describes the dominant term and ignores constant factors and lower order terms. Big O gives an upper bound: a function is O of g if it is at most a constant multiple of g for all sufficiently large inputs. Omega gives a lower bound and Theta gives a tight bound, meaning both an upper and a lower bound with possibly different constants. Common growth rates in increasing order are constant, logarithmic, linear, linearithmic, quadratic, cubic and exponential. A suitable diagram shows horizontal bands for the bounding functions and the algorithm curve staying within them beyond some input size. The time space tradeoff is the design choice in which extra memory is used to reduce running time, as when a hash table gives fast lookup at the cost of storage or when memoisation stores computed results to avoid recomputation. Worst case complexity bounds the behaviour on the most difficult input of a given size, average case is the expectation over a distribution and best case concerns the easiest input. A good answer defines complexity and each notation with inequalities, draws or describes the growth diagram, lists common orders and explains the time space tradeoff with a concrete example. Noting that constants matter in practice even though asymptotic notation ignores them shows a balanced understanding.

Result: Asymptotic notations classify the growth of time/space, and the time-space tradeoff shows that faster data structures and algorithms usually pay with extra storage, while space-saving ones pay with extra time.

f(n)=O(g(n))f(n) = O(g(n)) c>0c > 0 n0>=0n0 >= 0
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Asymptotic notations: O upper, Ω lower, Θ tight bound with c/n0 definitions
  • Growth order 1 < log n < n < n log n < n^2 < n^3 < 2^n < n!
  • Diagram axes: x = input size n, y = operations T(n); Θ is a band around g(n)
  • Time-space tradeoff: saving time usually needs extra storage and vice versa
  • Array: O(1) indexed access, O(n) insert; linked list: O(n) search, O(1) insert plus pointer overhead
  • Hash table: extra slots/chains buy O(1) average lookup; lower load factor is faster but larger
  • Merge sort: Θ(n log n) time and Θ(n) extra space; insertion sort: Θ(n^2) time and Θ(1) space
Q3b7MUnit 1 — Polynomial Representation and Addition Subtraction & Multiplications of Single variable & Two variables Polynomial
Core Concept

Illustrate how to represent the polynomial using linked list? Construct a program to add two polynomials using linked list.

1. Representation: A polynomial is stored as a list of term nodes, one per non-zero term, arranged in descending order of exponent. Each node has three fields:

| coefficient | exponent | next |

Example: p(x)=3x4+2x2+5p(x)=3x^4+2x^2+5 is [3|4] -> [2|2] -> [5|0] -> NULL. A zero coefficient term is omitted; a constant is a term with exponent 0. This saves space for sparse polynomials and allows exponent-aligned operations.

2. Addition algorithm: Walk both lists with pointers p and q. Compare exponents: if equal, add coefficients and append the term if the sum is non-zero and advance both; if p's exponent is larger, copy p's term; otherwise copy q's term. Append any remaining terms.

3. C program:

#include <stdio.h>
#include <stdlib.h>
typedef struct node { int coef, exp; struct node *next; } Node;
Node *append(Node *h, int c, int e) {
    Node *t = malloc(sizeof(Node)); t->coef=c; t->exp=e; t->next=NULL;
    if (!h) return t;
    Node *p=h; while(p->next) p=p->next; p->next=t; return h;
}
Node *add(Node *p, Node *q) {
    Node *r=NULL;
    while (p && q) {
        if (p->exp == q->exp) { int c=p->coef+q->coef;
            if (c) r=append(r,c,p->exp); p=p->next; q=q->next; }
        else if (p->exp > q->exp) { r=append(r,p->coef,p->exp); p=p->next; }
        else { r=append(r,q->coef,q->exp); q=q->next; }
    }
    while (p) { r=append(r,p->coef,p->exp); p=p->next; }
    while (q) { r=append(r,q->coef,q->exp); q=q->next; }
    return r;
}
void print(Node *p){ while(p){ printf("%dx^%d ",p->coef,p->exp); p=p->next; } printf("
"); }
int main(void){
    Node *a=NULL,*b=NULL;   /* a = 3x^4+2x^2+5, b = 4x^3-2x^2+1 */
    a=append(a,3,4); a=append(a,2,2); a=append(a,5,0);
    b=append(b,4,3); b=append(b,-2,2); b=append(b,1,0);
    printf("Sum: "); print(add(a,b));   /* 3x^4 + 4x^3 + 6x^0 */
    return 0;
}

Representing polynomials with linked nodes. A polynomial can be represented by a linked list in which each node stores a coefficient, an exponent and a pointer to the next term. Terms are kept in descending order of exponent, and only nonzero terms are stored, so sparse polynomials use much less memory than a dense array of all coefficients. To add two polynomials, advance two pointers through the lists and compare exponents at each step. If the exponents are equal, add the coefficients and create a term only if the sum is nonzero. If one exponent is larger, copy that term to the result and advance its pointer. Continue until both lists are exhausted. This runs in time proportional to the sum of the numbers of terms. Multiplication is done by multiplying every term of the first polynomial with every term of the second, adding exponents and multiplying coefficients, then combining terms that have equal exponents, either by inserting each product into an ordered result list or by collecting like terms in a table. For two variable polynomials each node can store two exponents or a coefficient and a pair of indices, and addition compares both exponents in order. A good answer draws a node structure with coefficient, exponent and next fields, shows a concrete example such as three x squared plus two x plus one as three linked nodes, gives the addition algorithm in pseudocode and explains the multiplication approach with its complexity. Mentioning that terms with zero coefficient must be dropped prevents the list from accumulating meaningless entries and is a common marking point.

Result: Each term is a node (coefficient, exponent, next); the merge-style add() walks both lists once, so addition takes O(m+n) for m and n terms.

p(x)=3x4+2x2+5p(x)=3x^4+2x^2+5
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Polynomial node = coefficient + exponent + next pointer; descending exponent order
  • Example 3x^4+2x^2+5 -> [3|4]->[2|2]->[5|0]->NULL
  • Addition compares exponents, adds equal ones, copies the larger exponent, then appends leftovers
  • Time O(m+n); sparse polynomials save memory because zero terms are absent
Q4a7MUnit 2 — Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues
Core Concept

Construct a Queue using a linked list? Include functions insert(), delete(), print(). Explain how a circular queue overcomes the limitations of a simple queue.

Answer: A linked queue keeps two pointers: front (next element to delete) and rear (last inserted node). insert() appends at rear, delete() removes from front, so the order is FIFO.

#include <stdio.h>
#include <stdlib.h>
typedef struct node { int data; struct node *next; } Node;
Node *front = NULL, *rear = NULL;
void insert(int x) {
    Node *p = malloc(sizeof(Node)); p->data=x; p->next=NULL;
    if (!front) front = rear = p; else { rear->next = p; rear = p; }
}
int delete(void) {
    if (!front) { puts("Underflow"); return -1; }
    Node *p = front; int x = p->data;
    front = front->next;
    if (!front) rear = NULL;
    free(p); return x;
}
void print(void) {
    for (Node *p=front; p; p=p->next) printf("%d ", p->data);
    puts("");
}
int main(void) { insert(10); insert(20); insert(30); print();
  printf("deleted %d
", delete()); print(); return 0; }

Output: 10 20 30, then deleted 10, then 20 30. Circular queue: In a simple array queue, repeated enqueue/dequeue pushes rear to the end and deleted slots are never reused, so a full condition occurs even when empty positions exist. A circular queue treats the array as a ring: after the last index the pointer wraps to 0 using (index+1) % size. front = (front+1) % size on delete and rear = (rear+1) % size on insert. Thus every freed slot is reused and the queue is full only when all N slots actually hold data.

A first in first out structure. A queue is a linear data structure in which insertion occurs at the rear and deletion at the front, so the first element inserted is the first removed. The operations are insert or enqueue, delete or dequeue, and tests for empty and full. A simple array implementation with front and rear indices suffers because deleted positions are never reused, so the array appears full even when empty slots exist at the beginning. A circular queue solves this by treating the array as a ring: after the last index the rear wraps to zero, and the queue is full only when the next position after rear is front. In a linked queue two pointers track the front and rear nodes, enqueue appends at the rear and dequeue removes from the front. A deque allows insertion and deletion at both ends and can be mapped into an array using front and rear indices that move in either direction with wraparound. A priority queue does not follow first in first out; each element has a priority and the element with the highest priority is removed first, often implemented with a heap. A good answer describes the operations, shows why the simple array overflows, explains the circular indexing with modulo arithmetic, gives the deque mapping with front and rear update rules and explains the significance of priority queues in scheduling and Dijkstra's algorithm. Noting that a circular queue reuses every location and therefore has constant time operations with no wasted space is the main point.

Result: Linked implementation gives O(1) insert/delete without shifting; circular arrangement reuses vacated slots and removes the false-full limitation of a linear array queue.

For n≥1n \ge 1 elements the operation uses O(1)O(1) extra space.

O(1)O(1)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Linked queue uses front and rear pointers; insert at rear, delete at front (FIFO)
  • insert: append node after rear and move rear; delete: remove head and advance front
  • Special case: deleting the last node resets rear to NULL
  • Circular queue wraps indices with modulo, reuses freed slots, and avoids false full condition
Q4b7MUnit 2 — Iteration and Recursion- Principles of recursion
Predicted

Construct a C program to check whether the parentheses are balanced in an expression.

Answer: A stack is the right structure: push every opening bracket; on a closing bracket, pop the top and verify that it is the matching opening bracket. At the end the stack must be empty.

#include <stdio.h>
#define MAX 100
char st[MAX]; int top = -1;
void push(char c) { if (top &lt; MAX-1) st[++top] = c; }
char pop(void) { return top >= 0 ? st[top--] : 0; }
int match(char a, char b) {
    return (a=='(' && b==')') || (a=='[' && b==']') || (a=='{' && b=='}');
}
int balanced(char s[]) {
    for (int i=0; s[i]; i++) {
        if (s[i]=='(' || s[i]=='[' || s[i]=='{') push(s[i]);
        else if (s[i]==')' || s[i]==']' || s[i]=='}') {
            if (top &lt; 0 || !match(pop(), s[i])) return 0;
        }
    }
    return top == -1;
}
int main(void) {
    char s[MAX]; scanf("%s", s);
    puts(balanced(s) ? "Balanced" : "Not balanced");
    return 0;
}

Trace: (a+[b]) pushes (, [; ] matches [; ) matches (; stack empty, so balanced. For ([)], ] meets top (, so mismatch and the string is rejected.

A function that calls itself. Recursion is a technique in which a function solves a problem by calling itself on a smaller instance. Every recursive definition needs a base case that stops the recursion and a recursive case that reduces the problem toward that base case. Without a reachable base case the calls continue until the run time stack overflows. Each call has its own local variables and return address stored on a call stack, so recursion uses more memory than an equivalent iterative loop, but the code can be much clearer for problems with a naturally recursive structure such as tree traversal, factorial, Fibonacci numbers and the Tower of Hanoi. Iteration uses explicit loops and a fixed set of variables, usually runs faster because there is no call overhead, and uses less stack space, but may be harder to express for branching structures. The Tower of Hanoi problem moves n disks from a source peg to a destination peg using an auxiliary peg by moving n minus one disks to the auxiliary, moving the largest disk to the destination and then moving the n minus one disks from auxiliary to destination. The number of moves satisfies M of n equals twice M of n minus one plus one, giving two to the power n minus one moves, so four disks require fifteen moves. A good answer defines recursion, states the base and recursive cases, explains the call stack, compares recursion with iteration in time, space and clarity, gives the Tower of Hanoi algorithm and traces the four disk case with a diagram or move list. Mentioning that tail recursion can be optimised into iteration by a compiler adds a useful nuance.

Result: The program prints "Balanced" only when each closing bracket matches the most recent unmatched opening bracket and the stack is empty at the end. Time O(n)O(n), space O(n)O(n).

O(n)O(n)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Push every opening bracket on a stack; pop and match on every closing bracket
  • Matching pairs: ( ), [ ], { }; reject if stack empty or pair mismatches
  • At the end the stack must be empty for a balanced expression
  • Example: (a+[b]) is balanced; ([)] is not. Time O(n), space O(n)
Q5a7MUnit 5 — Data Structure for Graph Representations: Adjacency Matrices
Predicted

Construct a Hash table that contains 10 buckets and uses linear probing to resolve collisions. The key values are integers and the Hash function used is key%10key \% 10. Insert values 43, 165, 62, 123, 142 in the table. Show all the steps and find the location of the key value 142?

Answer: Table size m=10, hash function h(key)=key%10h(key)=key \% 10. In linear probing, if the home slot is occupied we try (h+1) mod 10(h+1)\bmod 10, (h+2) mod 10(h+2)\bmod 10, ... until an empty bucket is found. Insertion steps:

Key Home Probe sequence Placed at
43 3 3 empty 3
165 5 5 empty 5
62 2 2 empty 2
123 3 3 occupied, try 4 4
142 2 2 occupied, 3 occupied, 4 occupied, 5 occupied, 6 empty 6
Final hash table (index 0..9):
0: -     1: -     2: 62    3: 43    4: 123
5: 165   6: 142   7: -     8: -     9: -

Fast lookup with a hash table. Hashing maps a key to an index in a table using a hash function, so that insertion, deletion and search take constant time on average. The division method uses the remainder of the key divided by the table size, and a table size that is prime often distributes keys better. Two different keys can map to the same index, which is a collision, and collision resolution is essential. In linear probing, a colliding key is placed in the next empty slot, searching cyclically. This is simple and has good cache behaviour, but it suffers from primary clustering: occupied slots form long contiguous runs that grow and make searches slow. Quadratic probing uses offsets of one, four, nine and so on instead of one, two, three, which reduces primary clustering because keys do not all pile into adjacent slots; however it can suffer secondary clustering because keys with the same initial index follow the same probe sequence, and it may fail to find an empty slot even when one exists unless the table size and probe range are chosen carefully. Chaining stores a linked list at each index and avoids clustering entirely at the cost of pointer storage. Double hashing uses a second hash function for the step size and gives good distribution. A good answer explains the division method, traces the insertion of the given keys into a ten bucket table, shows where key one hundred and forty two lands, describes clustering and explains how quadratic probing or chaining addresses it. Mentioning that the load factor, the ratio of stored keys to table size, strongly affects performance completes the discussion.

Result: Key 142 is stored at bucket 6 after four collisions (probe sequence 2, 3, 4, 5, 6). Searching for 142 follows the same chain starting at index 2.

h(key)=key%10h(key)=key \% 10 (h+1) mod 10(h+1)\bmod 10 (h+2) mod 10(h+2)\bmod 10
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
Hash table with 10 buckets, linear probing 31654362123142 053232 -> probe to 3 43 to 3, 165 to 5, 62 to 2, 123 to 3 occupied so 4, 142 to 2 occupied so 3,4 then 5 with ten buckets the probe sequence eventually finds the next free slot

Key Points

  • Hash function h(key) = key mod 10 with linear probing
  • 43 at 3, 165 at 5, 62 at 2, 123 at 4 after one collision
  • 142 probes 2, 3, 4, 5, 6 and is placed at index 6
  • Final table: index 2=62, 3=43, 4=123, 5=165, 6=142
Q5b7MUnit 3 — Merge Sort
Survival Mode

Demonstrate merge sort algorithm to sort the following elements in ascending order: 11, 16, 13, 11, 4, 12, 6, 7. What is the time and space complexity of merge sort?

Answer: Merge sort divides the list into halves until single elements, then merges sorted halves by repeatedly taking the smaller front element. Split: [11,16,13,11] and [4,12,6,7] -> [11,16], [13,11], [4,12], [6,7] -> singles. Merge level 1: [11,16] stays 11,16; [13,11] -> 11,13; [4,12] stays 4,12; [6,7] stays 6,7. Merge level 2: [11,16] + [11,13] -> 11,11,13,16; [4,12] + [6,7] -> 4,6,7,12. Merge level 3: [11,11,13,16] + [4,6,7,12] -> 4, 6, 7, 11, 11, 12, 13, 16. At each merge compare the two front items, copy the smaller to the output, and advance that pointer; copy the remainder when one side is exhausted. Duplicate 11s are kept, so the sort is stable. Complexity: recurrence T(n)=2T(n/2)+Θ(n)T(n)=2T(n/2)+\Theta(n) gives Θ(nlog⁡n)\Theta(n\log n) in best, average and worst cases. Auxiliary space is Θ(n)\Theta(n) for the temporary arrays (plus O(log n) recursion stack). It is not in-place but is stable and predictable.

Comparison based sorting methods. Selection sort repeatedly finds the smallest element in the unsorted part and swaps it into position. It has quadratic time in all cases, needs constant extra space and is simple but slow for large inputs. Insertion sort builds a sorted prefix by taking the next element and shifting larger elements right until the correct position is found. It is quadratic in the worst case but very fast on nearly sorted data and stable, and it also uses constant extra space. Merge sort divides the list into halves, sorts each recursively and merges the two sorted halves. It runs in n log n time in all cases but needs linear extra space for the merge arrays and is stable. Quick sort chooses a pivot, partitions the array so smaller elements go left and larger go right, and recurses. Its average time is n log n and it uses little extra space, but its worst case is quadratic when the pivot is consistently poor, such as choosing the smallest or largest element of an already sorted list. A good pivot such as the median of three or a random element makes bad behaviour unlikely. Binary search finds a target in a sorted array by comparing with the middle element and halving the search range each time, giving logarithmic time. A good answer gives the algorithm for the requested method, traces the given list through each pass or recursive split, states worst, average and best case complexities and extra space, and notes stability. Mentioning that merge sort is preferred for linked lists because merging needs no random access while quick sort is preferred for arrays because of locality shows practical judgement.

Result: Sorted list = 4, 6, 7, 11, 11, 12, 13, 16; time Θ(n log n), space Θ(n).

T(n)=2T(n/2)+Θ(n)T(n)=2T(n/2)+\Theta(n) Θ(nlog⁡n)\Theta(n\log n) Θ(n)\Theta(n)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.

Key Points

  • Divide into halves down to single elements, then merge sorted halves
  • Merge level 1: 11,16 | 11,13 | 4,12 | 6,7; level 2: 11,11,13,16 | 4,6,7,12
  • Final sorted list: 4, 6, 7, 11, 11, 12, 13, 16
  • Time Θ(n log n) in all cases; space Θ(n) for merge arrays; stable
Q6a7MUnit 5 — B Tree & Binary Heaps
Core Concept

Demonstrate B-Tree? Construct a B-tree of order 4 with the alphabets (letters) arrive in the sequence as follows: a g f b k d h m j e s i r x c l n t u p e.

Answer: A B-tree of order 4 is a balanced multiway tree in which each node holds at most 3 keys (and therefore at most 4 children); every non-root node has at least 1 key. Keys inside a node are sorted, and a full node is split before descending: its middle key moves up to the parent and the remaining keys form two nodes. All leaves stay at the same level, so search is O(log n). Construction highlights: a,g,f fill the root; inserting b splits it and promotes f, giving children a,b and g. Later inserts split the left child (promote d), then the right child (promote h). Inserting s splits the rightmost child and promotes m; inserting r promotes k to a new root; inserting c promotes b. The final duplicate e is ignored. Final B-tree of order 4:

                  [ f | k ]
          /          |          \
    [ b | d ]      [ h ]      [ m | r | t ]
    /   |   \      /   \      /   |   |   \
  [a] [c] [e]   [g] [i|j]  [l] [n|p] [s] [u|x]

Inorder sequence: a b c d e f g h i j k l m n p r s t u x - all incoming keys in sorted order.

A tree shaped array for priority access. A heap is a complete binary tree stored in an array that satisfies the heap property. In a max⁡\max heap every parent is at least as large as its children, so the largest element is at the root; in a min⁡\min heap every parent is at most its children. Because the tree is complete, the node at index i has children at two i plus one and two i plus two, and its parent at the floor of i minus one over two, so no pointers are needed. Insertion appends the new element at the end and bubbles it upward by swapping with its parent until the heap property is restored. Deletion of the root replaces it with the last element and bubbles it downward by swapping with the larger child until the property holds. Heap sort builds a max⁡\max heap from the array, then repeatedly swaps the root with the last unsorted element, reduces the heap size and restores the heap property. It runs in nlog⁡nn \log n time in all cases and uses constant extra space but is not stable. A B tree is a different structure, a balanced multiway search tree designed for disk storage. A B tree of order m has at most m children per node, keeps all leaves at the same level and stores keys in sorted order within each node, so each access touches few disk blocks. Insertion splits a full node and promotes the middle key. A good answer explains the array indexing of a heap, gives the insertion and deletion steps, traces the heap sort passes on the given list and describes B tree structure and insertion with splitting. Mentioning that heap operations take logarithmic time because the tree height is logarithmic ties the structure to its efficiency.

Result: The order-4 B-tree has root [f, k], three children [b,d], [h] and [m,r,t], with the leaves shown above; splits promote middle keys upward and keep the tree perfectly balanced.

max⁡\max min⁡\min nlog⁡nn \log n
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
B-tree of order 4 d | g | k a b ch i jr s t order 4: at most 3 keys and 4 children per node; split full nodes on insert

Key Points

  • Order-4 B-tree: at most 3 keys per node, at most 4 children; all leaves at one level
  • Insert into leaf; if full, split and promote the middle key to the parent
  • Final tree: root [f,k]; children [b,d], [h], [m,r,t] with leaves a,c,e / g,i,j / l,n,p,s,u,x
  • Inorder gives sorted keys a b c d e f g h i j k l m n p r s t u x
Q6b7MUnit 4 — Binary Search Tree
Survival ModePredictedRepeated

Construct a Binary Search Tree (BST) using the following sequence of numbers: 50, 30, 70, 20, 40, 80, 35, 45. Perform inorder traversal of Tree.

Answer: A Binary Search Tree is a binary tree in which, for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger than the node's key. Search, insert and delete take O(h)O(h) time, where h is the tree height (O(log n) if balanced). Inserting 10, 12, 5, 4, 20, 8, 7, 15, 13: 10 becomes root; 12 goes right; 5, 4 go left of 10; 8 goes right of 5; 7 goes left of 8; 20 goes right of 12; 15 goes left of 20; 13 goes right of 15.

            10
          /    \
         5      12
        / \       \
       4   8       20
          /        /
         7       15
                /
              13

Inorder traversal: 4, 5, 7, 8, 10, 12, 13, 15, 20 (always sorted).

Hierarchical data structures. A tree is a nonlinear structure consisting of nodes connected by edges, with one root node and a parent child relationship. Important terms include root, parent, child, sibling, leaf, internal node, degree, level, height and depth. A binary tree has at most two children per node, and a binary search tree adds the rule that values in the left subtree are smaller than the node and values in the right subtree are larger, so insertion and search take time proportional to the height. Inserting the given sequence into a binary search tree places each new value by comparing with the root and descending until an empty child is found. An AVL tree is a self balancing binary search tree in which the heights of the left and right subtrees of every node differ by at most one. After an insertion, the balance factor of ancestors is updated and the first unbalanced node is repaired by a single or double rotation depending on whether the insertion was into the outer or inner side. A complete binary tree fills every level except possibly the last, with nodes as far left as possible, which makes it ideal for array based heap storage. An extended binary tree adds external null nodes to make every internal node have exactly two children, and this device leads to the relation between external and internal path lengths. Huffman coding uses a binary tree in which more frequent characters are placed nearer the root, so their code words are shorter; the tree is built by repeatedly combining the two lowest probabilities until one root remains, and the average code length is the sum of probability times code length. A good answer defines the terms, draws the requested trees or gives the insertion sequence with rotations, states the path length proof by induction on the number of internal nodes, and explains the Huffman construction with the computed average length. Mentioning that balancing keeps height logarithmic and therefore keeps search efficient is the key idea linking the topics.

Result: The constructed BST has root 10 as shown; its inorder sequence is the sorted input keys.

O(h)O(h)
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
10 512 4820 715 left subtree smaller, right subtree larger at every node

Key Points

  • BST property: left subtree keys < node key < right subtree keys
  • Insertion walk: compare with node and go left or right until an empty child is found
  • Resulting tree: 10 root; left 5 (4, 8 with 7); right 12 (20 with 15 and 13)
  • Inorder traversal gives sorted order 4, 5, 7, 8, 10, 12, 13, 15, 20
Q7a7MUnit 5 — Data Structure for Graph Representations: Adjacency Matrices
Survival ModePredicted

Explain two ways to represent a graph in memory and compare their advantages: (i) Adjacency Matrix (ii) Adjacency List

Answer: (i) Adjacency Matrix: a V×VV\times V array A where A[i][j] = 1 (or the edge weight) if edge i-j exists, else 0. For an undirected graph the matrix is symmetric. Space Θ(V²) regardless of edges. Advantage: edge existence/test and weight lookup are O(1); simple for dense graphs and easy matrix operations. Disadvantage: wasteful for sparse graphs; adding a vertex costs O(V²).

For edges (0,1),(0,2),(1,2),(2,3):
    0 1 2 3
 0  0 1 1 0
 1  1 0 1 0
 2  1 1 0 1
 3  0 0 1 0

(ii) Adjacency List: an array of V linked lists; list i contains every vertex adjacent to i. Space Θ(V+E). Advantage: compact for sparse graphs, easy to iterate over only the actual neighbours, adding a vertex/edge is cheap. Disadvantage: testing whether a specific edge exists takes O(degree(i)).

0 -> 1 -> 2
1 -> 0 -> 2
2 -> 0 -> 1 -> 3
3 -> 2

Representing and exploring graphs. A graph consists of a set of vertices and a set of edges connecting pairs of vertices. A weighted graph assigns a numerical cost to each edge, and the degree of a vertex is the number of edges incident on it; in a directed graph this splits into indegree and outdegree. A regular graph of degree d with n vertices has n times d divided by two edges because each edge is counted at both endpoints. Graphs are represented in memory either by an adjacency matrix or by an adjacency list. An adjacency matrix is a square array where entry i j records the presence or weight of an edge, so testing an edge is constant time and indegree and outdegree are found by summing a row and a column, but it uses order n squared space and is wasteful for sparse graphs. An adjacency list stores for each vertex a list of its neighbours, using space proportional to vertices plus edges and allowing quick iteration over neighbours, but testing a specific edge takes time proportional to the degree. Depth first search explores as far as possible along one branch before backtracking, using a stack or recursion, while breadth first search explores level by level using a queue. Connected components are found by running a traversal from each unvisited vertex and collecting all vertices reached. A good answer defines the terms, compares the two representations with a table, shows how indegree and outdegree are computed from a matrix, explains the traversal data structures and gives the connected component algorithm. Noting that matrix representation is preferred for dense graphs and list representation for sparse graphs is the practical conclusion.

Result: Use a matrix for dense graphs with frequent edge-existence queries (O(1), Θ(V²) space); use a list for sparse graphs (Θ(V+E) space, efficient traversal).

V×VV\times V
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
Adjacency matrix versus adjacency list matrix: n x nedge test O(1)space O(n^2) ABC list: space O(V+E), iterate neighbours quickly

Key Points

  • Adjacency matrix: V×V array, A[i][j]=1/weight if edge exists; O(1) edge test, Θ(V²) space
  • Adjacency list: array of neighbour lists; Θ(V+E) space, efficient neighbour iteration
  • Matrix is good for dense graphs; list is good for sparse graphs
  • Undirected graph matrix is symmetric; list stores each edge twice
Q7b7MUnit 5 — Terminology used with Graph
Core Concept

Explain the following graph terminologies with examples: (i) Graph (ii) Weighted Graph (iii) Degree of a Vertex

Answer: (i) Graph: A graph G = (V, E) is a set of vertices V and a set of edges E connecting pairs of vertices. In an undirected graph edges have no direction, e.g. V=A,B,C,E=(A,B),(B,C)V={A,B,C}, E={(A,B),(B,C)}; in a directed graph (digraph) edges are ordered arcs, e.g. A->B, B->C. Graphs model road networks, friendship networks and dependencies. (ii) Weighted graph: A graph in which each edge carries a numerical weight/cost, e.g. A--5--B, B--3--C. Weights may represent distance, time or cost; weighted graphs are used to find shortest paths (Dijkstra) and minimum spanning trees (Prim/Kruskal). A graph without weights can be viewed as all weights equal to 1. (iii) Degree of a vertex: The number of edges incident on a vertex. In the undirected graph V=A,B,C,E=(A,B),(B,C),deg(A)=1,deg(B)=2,deg(C)=1V={A,B,C}, E={(A,B),(B,C)}, deg(A)=1, deg(B)=2, deg(C)=1; the sum of degrees is 2|E|. In a directed graph we distinguish indegree (incoming arcs) and outdegree (outgoing arcs): for arcs A->B, A->C, B->C, vertex A has outdeg 2 and indeg 0, B has indeg 1 and outdeg 1, C has indeg 2 and outdeg 0. A vertex with degree 0 is isolated.

Representing and exploring graphs. A graph consists of a set of vertices and a set of edges connecting pairs of vertices. A weighted graph assigns a numerical cost to each edge, and the degree of a vertex is the number of edges incident on it; in a directed graph this splits into indegree and outdegree. A regular graph of degree d with n vertices has n times d divided by two edges because each edge is counted at both endpoints. Graphs are represented in memory either by an adjacency matrix or by an adjacency list. An adjacency matrix is a square array where entry i j records the presence or weight of an edge, so testing an edge is constant time and indegree and outdegree are found by summing a row and a column, but it uses order n squared space and is wasteful for sparse graphs. An adjacency list stores for each vertex a list of its neighbours, using space proportional to vertices plus edges and allowing quick iteration over neighbours, but testing a specific edge takes time proportional to the degree. Depth first search explores as far as possible along one branch before backtracking, using a stack or recursion, while breadth first search explores level by level using a queue. Connected components are found by running a traversal from each unvisited vertex and collecting all vertices reached. A good answer defines the terms, compares the two representations with a table, shows how indegree and outdegree are computed from a matrix, explains the traversal data structures and gives the connected component algorithm. Noting that matrix representation is preferred for dense graphs and list representation for sparse graphs is the practical conclusion.

Result: A graph is vertices plus edges; a weighted graph adds a cost to each edge; the degree counts incident edges (indegree and outdegree for directed graphs).

V=A,B,C,E=(A,B),(B,C)V={A,B,C}, E={(A,B),(B,C)} V=A,B,C,E=(A,B),(B,C),deg(A)=1,deg(B)=2,deg(C)=1V={A,B,C}, E={(A,B),(B,C)}, deg(A)=1, deg(B)=2, deg(C)=1
Tip from Examiner: State the structure or algorithm, show the key steps with a diagram or trace, and give the resulting complexity or values with units.
ABCD graph = vertices plus edges; weighted graph has costs; degree counts incident edges

Key Points

  • Graph G=(V,E): vertices connected by edges; directed graphs use arcs
  • Weighted graph: each edge has a numerical cost used by shortest-path/MST algorithms
  • Degree = number of incident edges; sum of degrees = 2|E| in undirected graphs
  • Directed graphs split degree into indegree and outdegree