Top Banner Ad
BCS301 · 2023-2422 Questions

DATA STRUCTURE — 2023-24

Section A

2 Marks Each · 7 questions
Q1a2MUnit 1 — Asymptotic notations: Big Oh
Survival ModePredictedRepeated

What are the various asymptotic notations?

1. Meaning of complexity: Complexity measures how the resource use of an algorithm grows as the input size nn grows. Time complexity T(n)T(n) counts elementary operations (comparisons, assignments, arithmetic) as a function of nn; space complexity S(n)S(n) counts memory cells used. Auxiliary space is the extra space beyond the input. We study worst case (maximum over inputs of size n), average case (expected) and best case (minimum), and use asymptotic estimates so that constants and small inputs do not hide the growth trend.

2. Formal asymptotic definitions (f, g nonnegative):

  • Big Oh: f(n)=O(g(n))f(n) = O(g(n)) iff there exist c>0c > 0 and n0>=0n0 >= 0 such that 0<=f(n)<=cg(n)0 \lt = f(n) \lt = c g(n) for every n>=n0n >= n0. The function gg is an eventual upper bound.
  • Omega: f(n)=Ω(g(n))f(n) = Ω(g(n)) iff there exist c>0c > 0 and n0>=0n0 >= 0 such that 0<=cg(n)<=f(n)0 \lt = c g(n) \lt = f(n) for every n>=n0n >= n0. The function gg is an eventual lower bound.
  • Theta: f(n)=Θ(g(n))f(n) = Θ(g(n)) iff there exist c1>0c1 > 0, c2>0c2 > 0 and n0>=0n0 >= 0 such that 0<=c1g(n)<=f(n)<=c2g(n)0 \lt = c1 g(n) \lt = f(n) \lt = c2 g(n) for every n>=n0n >= n0; that is, Θ(g)=O(g)Θ(g) = O(g) intersect Ω(g)Ω(g), a tight bound.
  • Strict forms: f(n)=o(g(n))f(n) = o(g(n)) when f(n)/g(n)−>0f(n)/g(n) -> 0; f(n)=ω(g(n))f(n) = ω(g(n)) when f(n)/g(n)−>infinityf(n)/g(n) -> infinity.

3. Common growth-rate order (slowest to fastest): 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!. Examples: array access 11; binary search lognlog n; linear search nn; merge sort nlognn log n; triple matrix loop n3n^3; subset enumeration 2n2^n; all permutations n!n!.

4. Suitable qualitative growth diagram:

Operations / time T(n)
 ^
 |                                             n!
 |                                        _.-'
 |                                   _.-' 2^n
 |                             _.-'
 |                       _.-' n^3
 |                  _.-' n^2
 |            _____/ n log n
 |        ___/ n
 |    ___/ log n
 |___/__________________________________________> input size n

The x-axis is input size nn and the y-axis is operations / running time T(n)T(n). The curves lie close for small nn but separate for large nn, which is why constant factors are ignored. A Θ bound places ff between two multiples of gg beyond n0n0:

T(n)
 ^        . . . . . . c2*g(n)   upper bound
 |      .   f(n)
 |    .   /
 |  . . . . . . . . c1*g(n)   lower bound
 +---------------------------> n

5. Application to the asked question: For f(n)=3n+5f(n) = 3n + 5 with g(n)=ng(n) = n: 3n+5<=8n3n+5 \lt = 8n for n>=2n >= 2, so f=O(n)f = O(n); also 3n+5>=3n3n+5 >= 3n, so f=Ω(n)f = Ω(n); hence f=Θ(n)f = Θ(n). Binary search is Θ(logn)Θ(log n), linear search Θ(n)Θ(n) and merge sort Θ(nlogn)Θ(n log n); the growth-rate order tells us which stays faster as nn increases.

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: Complexity is the growth of time/space with nn; O, Ω and Θ bound it above, below and tightly, and the diagram shows the standard growth-rate ladder.

T(n)T(n) S(n)S(n) f(n)=O(g(n))f(n) = O(g(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.
Asymptotic growth comparison log n n n^2 input size noperations Big O bounds above, Omega below, Theta both sides for large n

Key Points

  • Complexity T(n)/S(n) measures time/memory as a function of input size n
  • Worst, average and best case; auxiliary space is extra space
  • O: 0 <= f(n) <= c g(n) for n >= n0 (upper bound)
  • Ω: 0 <= c g(n) <= f(n) for n >= n0 (lower bound)
  • Θ: c1 g(n) <= f(n) <= c2 g(n) for n >= n0 (tight bound)
  • 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); curves diverge for large n
  • Example: 3n+5 is Θ(n); binary search Θ(log n); merge sort Θ(n log n)
Q1b2MUnit 2 — Application of stack: Prefix and Postfix Expressions
Survival ModePredicted

Why are parentheses needed to specify the order of operations in infix expressions but not in postfix operations?

Infix expressions need parentheses because an operator between two operands does not uniquely define grouping when several operators appear; precedence and associativity help but cannot remove all ambiguity. In postfix the operator follows its operands and the position fixes the grouping completely, so the order of evaluation is unambiguous without parentheses.

Key Points

  • Infix grouping is ambiguous
  • Precedence rules are incomplete
  • Postfix order is unambiguous
Q1c2MUnit 3 — Quick Sort
Core Concept

How the choice of pivot element effects the running time of quick sort algorithm?

Pivot choice strongly affects quick sort. A pivot near the median divides the array into two nearly equal halves and gives n log n behaviour. Consistently choosing the smallest or largest pivot produces one empty side and one side of size n minus one, degrading to quadratic time. Random or median of three pivots make this unlikely.

Key Points

  • Median pivot balances partitions
  • Extreme pivot degrades to O(n^2)
  • Random choice reduces risk
Q1d2MUnit 3 — Concept of Hashing & Collision resolution Techniques used in Hashing
Survival ModePredicted

What are the 2 different forms of hashing?

The two common hashing forms are hashing with collision resolution by open addressing, where all keys are stored in the table itself using linear or quadratic probing, and separate chaining, where each table slot points to a linked list of keys that hash to that slot. Open addressing saves pointers; chaining avoids clustering.

Key Points

  • Open addressing puts keys in table
  • Chaining uses linked lists
  • Different clustering behaviour
Q1e2MUnit 4 — Huffman coding using Binary Tree
Core Concept

What is the significance of binary tree in Huffman algorithm?

A binary tree is significant in Huffman coding because each combine step creates a node with two children and the root to leaf paths produce binary code words. Since codes are read as paths, no code can be a prefix of another, giving an instantly decodable prefix code. Frequent symbols are placed nearer the root and receive shorter codes.

Key Points

  • Two children per internal node
  • Root-leaf paths give codes
  • Prefix-free and optimal
Q1f2MUnit 5 — Terminology used with Graph
Survival ModePredicted

What is the number of edges in a regular graph of degree d and n vertices.

In a regular graph every vertex has degree d. The sum of all vertex degrees is n times d, and by the handshaking lemma this equals twice the number of edges because each edge contributes to two vertices. Hence the number of edges is n d divided by two, assuming d times n is even.

Key Points

  • Sum of degrees is n d
  • Handshaking lemma
  • Edges equal n d over 2
Q1g2MUnit 5 — Connected Component
Core Concept

Write an algorithm to obtain the connected components of a graph.

To find connected components, mark all vertices unvisited. For each unvisited vertex, start a depth first or breadth first search, collect every vertex reached into one component, and repeat until no unvisited vertices remain. Each traversal visits exactly one component, so the number of traversals equals the number of connected components.

Key Points

  • Start traversal at unvisited vertex
  • Collect all reached vertices
  • Repeat until none remain

Section B

7 Marks Each · 5 questions
Q2a7MUnit 1 — Operations on a Linked List
Core Concept

Write a Pseudo code that will concatenate two linked lists. Function should have two parameters, pointers to the beginning of the lists and the function should link second list at the end of the first list.

Approach: To concatenate list2 after list1, walk to the last node of list1 (the node whose next NULL) and make its next point at the head of list2. No nodes are copied, so the operation is O(n)O(n) for the length of the first list and O(1) extra space.

Pseudo code:

Function concatenate(first, second):
    if first == NULL: return second       // nothing to attach to
    if second == NULL: return first       // nothing to attach
    p = first
    while p->next != NULL:                // find the last node of list1
        p = p->next
    p->next = second                      // link second list at the end
    return first                          // head of combined list

Trace: first = 10 -> 20 -> NULL, second = 30 -> 40 -> NULL. Starting at 10, the loop stops at 20; setting 20->next = 30 gives 10 -> 20 -> 30 -> 40 -> NULL. Note: If the second list must remain independent, copy its nodes instead; otherwise both lists now share the appended suffix and the caller must not free them twice.

Chaining nodes together. A linked list is a linear data structure in which each element is a separate node containing a data field and one or more pointers to other nodes. Unlike an array, the nodes need not occupy consecutive memory locations, so insertion and deletion do not require shifting elements, but random access is not possible and traversal must start from the head. In a singly linked list each node points to the next node and the last node points to null. To insert a node after a given node, allocate a new node, set its next pointer to the given node's next pointer, and then set the given node's next pointer to the new node; the order matters or the rest of the list is lost. To concatenate two lists, traverse the first list to its last node and set that node's next pointer to the head of the second list, then return the head of the first. A doubly linked list node has both a next and a previous pointer, which allows traversal in either direction and deletion given only a pointer to the node, at the cost of one extra pointer per node. A circular list makes the last node point back to the first, which is useful for round robin scheduling and for queues implemented in a ring. A good answer draws the node structure, gives pseudocode for the requested operation with clear pointer update order, states the time complexity of traversal and insertion and contrasts linked storage with array storage. Mentioning that access by index takes linear time while insertion at a known position takes constant time is the essential tradeoff.

Result: The single pointer assignment lastNode->next = second concatenates the lists, after traversing the first list to its tail.

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

  • Traverse first list until p->next == NULL to locate its tail
  • Then set p->next = second (head of the second list) and return first
  • Handle empty-list cases: empty first returns second; empty second returns first
  • Time O(n) for the first list, O(1) extra space; no node copying
Q2b7MUnit 2 — Application of stack: Prefix and Postfix Expressions
Survival ModePredictedRepeated

Write an algorithm to convert a valid arithmetic infix expression into an equivalent postfix expression. Trace your algorithm for following infix expression. A+B∗C−D/FA+B*C-D/F

1. Algorithm (stack-based infix to postfix): Precedence: ^ = 3 (right-associative), * and / = 2, + and - = 1.

  1. Add a sentinel ) to the expression and push ( on an empty stack.
  2. Scan left to right:
    • operand -> append to output;
    • ( -> push;
    • ) -> pop operators to output until ( is popped;
    • operator op -> while the stack top is an operator with higher precedence, or equal precedence and op is left-associative, pop it to output; then push op.
  3. At the sentinel, pop all operators to output.

2. Trace of A+(B∗C−(D/EF)∗G)∗HA+(B*C-(D/E^F)*G)*H:

Token Stack (bottom->top) Output so far
A ( A
+ ( + A
( ( + ( A
B ( + ( AB
* ( + ( * AB
C ( + ( * ABC
- ( + ( - ABC*
( ( + ( - ( ABC*
D ( + ( - ( ABC*D
/ ( + ( - ( / ABC*D
E ( + ( - ( / ABC*DE
^ ( + ( - ( / ^ ABC*DE
F ( + ( - ( / ^ ABC*DEF
) ( + ( - ABC*DEF^/
* ( + ( - * ABC*DEF^/
G ( + ( - * ABC*DEF^/G
) ( + ABCDEF^/G-
* ( + * ABCDEF^/G-
H ( + * ABCDEF^/G-H
end (empty) ABCDEF^/G-H*+

Note that the final * H multiplies the whole A+(...) result, because * has higher precedence than + and there are no outer parentheses.

Converting and evaluating expressions. An infix expression places the operator between its operands and needs parentheses and precedence rules to remove ambiguity. A postfix expression places the operator after its operands and is unambiguous without parentheses because the order of operators is exactly the order of evaluation. A prefix expression places the operator before its operands, also called polish notation. To convert infix to postfix, scan the expression from left to right, output operands immediately, push opening parentheses and operators onto a stack, pop operators of higher or equal precedence to the output before pushing a new operator, and on a closing parenthesis pop until the matching opening parenthesis. After the scan, pop all remaining operators. For the given expression with nested parentheses and an exponent, the trace shows the stack growing and shrinking at each step and the output accumulating operands and operators in postfix order. To evaluate a postfix expression, scan left to right, push operands onto a stack, and when an operator appears pop the top two operands, apply the operator and push the result. Evaluating three times the quantity five minus three therefore pushes three, five and three, subtracts to two, multiplies by three and yields six. Parentheses are needed only in infix because the position of an operator alone does not determine which operands it joins; in postfix the position fixes the grouping completely. A good answer gives the algorithm, traces the stack and output at each significant step, states the final expression and evaluates a sample expression with the stack contents shown.

Result: Postfix expression = ABCDEF^/G-H+* (equivalently spaced: A B C * D E F ^ / G * - H * +).

A+(B∗C−(D/EF)∗G)∗HA+(B*C-(D/E^F)*G)*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.

Key Points

  • Algorithm: operands to output; operators pushed/popped by precedence; parentheses popped on ')'
  • Precedence ^ > *, / > +, -; ^ is right-associative
  • Key intermediate: (D/E^F) -> DEF^/ ; (BC-...G) -> ABCDEF^/G-
  • Final postfix of A+(BC-(D/E^F)G)H = ABCDEF^/G-H+
  • Stack size is O(n); total time O(n)
Q2c7MUnit 3 — Concept of Hashing & Collision resolution Techniques used in Hashing
Survival ModePredicted

What are the disadvantages of linear probing in hashing? Discuss how quadratic probing can be used to solve some of these problems.

Answer: In linear probing the probe sequence is h,h+1,h+2,…(modm)h, h+1, h+2, \ldots \pmod m. Its drawbacks are:

  1. Primary clustering: colliding keys form long consecutive runs; a new key whose home is anywhere before a cluster must walk through the whole cluster, so search/insert degrades towards O(n). Clusters also merge when they touch.
  2. Uneven use: some regions fill while other buckets remain empty, raising the load factor locally.
  3. Deletion is delicate: a simple empty mark breaks searches, so slots must be marked DELETED; performance then depends on those tombstones. Quadratic probing uses hi=(h+c1i+c2i2) mod mh_i = (h + c_1 i + c_2 i^2) \bmod m. Successive probes jump 1, 4, 9, ... slots instead of stepping by one, so keys with the same home index spread out and long primary clusters do not form. Example with m=11, h=2: probes 2, 3, 6, 0, 7, ... If key 25 and key 36 both hash to 2, 36 is placed at 3 and the next one at 6 rather than extending a block 2,3,4,5. Limitation: quadratic probing with c1=c2=1c_1=c_2=1 and m a power of two visits only about half the table; choose m prime and keep load factor at or below 0.5 to guarantee finding an empty slot. Secondary clustering (same home gives same probe path) remains.

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: Quadratic probing reduces primary clustering and improves average lookup time; linear probing is simpler but suffers badly from clustering as the table fills.

h,h+1,h+2,…(modm)h, h+1, h+2, \ldots \pmod m hi=(h+c1i+c2i2) mod mh_i = (h + c_1 i + c_2 i^2) \bmod m c1=c2=1c_1=c_2=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

  • Linear probing probes h, h+1, h+2: causes primary clustering and long searches
  • Clusters merge; deletion needs a DELETED marker to keep chains searchable
  • Quadratic probing: (h + c1i + c2i^2) mod m spreads same-home keys apart
  • Example m=11, h=2 gives probes 2,3,6,0,7; keep load factor <= 0.5 for a prime table size
Q2d7MUnit 4 — Tree Traversal algorithms: Inorder
Core Concept

Write C function for non-recursive post order traversal.

Answer: In postorder a node is visited only after both subtrees. The iterative version uses an explicit stack and a prev pointer that records the last visited node, so we can tell whether a node's right subtree has already been processed.

#include <stdio.h>
#define MAX 100
typedef struct node { int data; struct node *left, *right; } Node;
void postorder(Node *root) {
    Node *st[MAX], *cur = root, *prev = NULL;
    int top = 0;
    while (cur || top > 0) {
        while (cur) { st[top++] = cur; cur = cur->left; }
        Node *p = st[top-1];
        if (p->right && prev != p->right) cur = p->right;
        else { printf("%d ", p->data); prev = st[--top]; }
    }
}

How it works: push the left spine; look at the top. If it has an unvisited right child, descend there; otherwise print it and pop. prev prevents re-descending into the same right subtree. For a tree rooted at A with left child B and right child C the output is B, C, A. Time O(n)O(n), space O(h)O(h).

Visiting every node systematically. Tree traversal is the process of visiting each node exactly once in a defined order. The three depth first traversals are named by when the root is visited relative to its subtrees. In preorder the root is visited first, then the left subtree, then the right subtree. In inorder the left subtree is visited first, then the root, then the right subtree; for a binary search tree this yields the keys in sorted order. In postorder the left and right subtrees are visited before the root, which is useful when a parent must be processed after its children, for example when freeing nodes or computing subtree sizes. Recursive implementations are straightforward, but a non recursive postorder traversal can be built with an explicit stack by pushing the root, repeatedly going down left children, then examining the top of the stack to decide whether a right subtree remains or the node can be visited, using a last visited marker. A threaded binary tree replaces null child pointers with threads to the inorder predecessor or successor, making inorder traversal possible without recursion or a stack and allowing efficient finding of the next node, at the cost of extra flag bits and more complex insertion and deletion. A good answer defines each traversal, gives the recursive order, explains the non recursive postorder algorithm with stack operations and explains how threading works and why it is useful. Showing the visit order on a small tree ties the abstract order to a concrete example and makes the answer easier to verify.

Result: The function prints nodes in left-right-root order without recursion, using a stack of at most the tree height.

O(n)O(n) 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.
Non-recursive postorder with a stack A BC DE push left spine, then visit node when right child done; order D E B C A

Key Points

  • Non-recursive postorder needs a stack plus a prev pointer
  • Push left spine; if top has an unprocessed right child, descend into it
  • Otherwise visit top and pop; prev records the last printed node
  • Visits left, right, root; time O(n), space O(h)
Q2e7MUnit 5 — Transitive Closure and Shortest Path algorithm: Warshal Algorithm and Dijikstra Algorithm
Core Concept

Consider the following graph and using Dijkstra Algorithm find the shortest path.

Answer: Dijkstra's algorithm finds the shortest paths from one source to all other vertices in a graph with non-negative edge weights. Algorithm:

  1. Set dist[source]=0dist[source]=0 and dist[v]=∞dist[v]=\infty for all others; mark all vertices unvisited.
  2. Pick the unvisited vertex u with the smallest dist[u] (a priority queue gives O(log V)).
  3. For each unvisited neighbour v of u, if dist[u]+weight(u,v) < dist[v], update dist[v] and record predecessor[v]=upredecessor[v]=u.
  4. Mark u visited and repeat until all vertices are visited. Illustration with directed edges A→B=4,A→C=2,C→B=1,B→D=5,C→D=8A\rightarrow B=4, A\rightarrow C=2, C\rightarrow B=1, B\rightarrow D=5, C\rightarrow D=8, source A: | Step | Settled | dist(B) | dist(C) | dist(D) | | --- | --- | --- | --- | --- | | init | - | 4 (via A) | 2 (via A) | ∞ | | 1 | C | 3 (A-C-B) | 2 | 8 | | 2 | B | 3 | 2 | 8 (A-C-B-D) | | 3 | D | 3 | 2 | 8 | Shortest paths: A->C = 2 (A-C); A->B = 3 (A-C-B, better than direct 4); A->D = 8 (A-C-B-D, better than A-C-D = 10).

Spanning trees and shortest paths. A spanning tree connects all vertices of a connected graph with exactly n minus one edges and no cycles. A minimum spanning tree is the spanning tree with the smallest total edge weight. Prim's algorithm starts from one vertex and repeatedly adds the cheapest edge that connects a vertex in the growing tree to a vertex outside it. Kruskal's algorithm sorts all edges by weight and adds each edge if it does not form a cycle, using a disjoint set structure to test connectivity. Both produce a minimum spanning tree, Prim being better for dense graphs and Kruskal for sparse graphs. Shortest path problems differ: Dijkstra's algorithm finds the shortest path from one source to all other vertices in a graph with nonnegative weights by repeatedly selecting the unvisited vertex with the smallest tentative distance and relaxing its outgoing edges. Floyd Warshall finds shortest paths between every pair of vertices by dynamic programming, considering each vertex as a possible intermediate point and updating the distance matrix. The transitive closure of a graph records which vertices are reachable from which others and can be computed by the same Warshall iteration using boolean values. A good answer distinguishes minimum spanning tree from shortest path, gives the steps of each algorithm, applies Prim or Dijkstra to the given graph with a table of selected edges or tentative distances, states complexities and explains what the matrix update means. Mentioning that Dijkstra fails with negative edges while Bellman Ford handles them is a useful boundary condition, and noting that a minimum spanning tree minimises total weight while a shortest path minimises one route shows the essential conceptual difference.

Result: Dijkstra repeatedly settles the nearest unsettled vertex; time O(V²) with an array or O((V+E) log⁡\log V) with a heap. It requires non-negative weights; for the illustrated graph the shortest A-to-D distance is 8.

dist[source]=0dist[source]=0 dist[v]=∞dist[v]=\infty predecessor[v]=upredecessor[v]=u
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.
Dijkstra shortest paths ABCD 4236 settle nearest unsettled vertex, relax outgoing edges, repeat

Key Points

  • Dijkstra: repeatedly settle the unvisited vertex with minimum dist
  • Relax each edge: if dist[u]+w(u,v) < dist[v], update dist[v] and predecessor
  • Requires non-negative edge weights; O(V²) array or O((V+E) log V) heap
  • Example from A: dist C=2, B=3 via C, D=8 via C-B

Section C

7 Marks Each · 10 questions
Q3a7MUnit 1 — Representation of Arrays: Row Major Order
Survival Mode

Each element of an array Data [20][50] requires 4 bytes of storage. Base address of Data is 2000. Determine the location of Data [10][10] when the array is stored as: (i) Row major (ii) Column major

Given: Data[20][50]Data[20][50]: 20 rows, 50 columns; element size = 4 bytes; base = 2000. Indices are 0-based, so i=10i=10, j=10j=10.

(i) Row-major order (last subscript varies fastest): Address(i,j)=Base+(i×Nc+j)×sizeAddress(i,j) = Base + (i \times N_c + j)\times size =2000+(10×50+10)×4=2000+510×4=2000+2040== 2000 + (10\times50 + 10)\times4 = 2000 + 510\times4 = 2000+2040 = 4040.

(ii) Column-major order (first subscript varies fastest): Address(i,j)=Base+(j×Nr+i)×sizeAddress(i,j) = Base + (j \times N_r + i)\times size =2000+(10×20+10)×4=2000+210×4=2000+840== 2000 + (10\times20 + 10)\times4 = 2000 + 210\times4 = 2000+840 = 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: Row-major location = 4040; column-major location = 2840. Row-major skips 10 full rows of 50 elements, column-major skips 10 full columns of 20 elements.

Data[20][50]Data[20][50] i=10i=10 j=10j=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.

Key Points

  • Data[20][50]: 20 rows, 50 columns, 4 bytes per element, base 2000
  • Row-major: Address = 2000 + (10*50 + 10)*4 = 4040
  • Column-major: Address = 2000 + (10*20 + 10)*4 = 2840
  • Row-major makes the column index vary fastest; column-major makes the row index vary fastest
Q3b7MUnit 1 — Polynomial Representation and Addition Subtraction & Multiplications of Single variable & Two variables Polynomial
Core Concept

How will you create link list representation of a polynomial. Explain it with the suitable example.

1. Idea: A sparse polynomial is stored as a singly linked list of its non-zero terms, in descending exponent order. Each node contains coefficient, exponent and a next pointer:

| coef | exp | next | ---> | coef | exp | next | ---> ... ---> NULL

2. Example: p(x)=4x5+3x3−2x+7p(x) = 4x^5 + 3x^3 - 2x + 7 becomes [4|5] -> [3|3] -> [-2|1] -> [7|0] -> NULL. Terms with zero coefficient are omitted, e.g. x4x^4 and x2x^2 here do not appear. A pure constant is one node with exponent 0; the zero polynomial is an empty list (or a single node with coefficient 0).

3. Creation steps:

  1. Read each term (coefficient, exponent).
  2. Allocate a node with malloc, fill the fields, set next = NULL.
  3. Insert it at the tail (or in descending-exponent position to keep the list sorted).
  4. Repeat until all terms are entered; keep a head pointer.

4. Why useful: Addition/subtraction/multiplication scan the lists and combine equal exponents; memory equals the number of non-zero terms, not the maximum degree, so sparse high-degree polynomials are handled efficiently.

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: A polynomial is represented by a linked list of (coefficient, exponent) nodes sorted by exponent, e.g. 4x5+3x3−2x+74x^5+3x^3-2x+7 as four linked nodes.

p(x)=4x5+3x3−2x+7p(x) = 4x^5 + 3x^3 - 2x + 7 x4x^4 x2x^2
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

  • Each node stores coefficient, exponent and next pointer
  • Nodes kept in descending exponent order; zero-coefficient terms omitted
  • Example: 4x^5+3x^3-2x+7 -> [4|5]->[3|3]->[-2|1]->[7|0]->NULL
  • Creation: malloc a node per term and link it at the tail/in sorted position; head pointer starts the list
Q4a7MUnit 2 — Evaluation of postfix expression
Core Concept

Write an algorithm to evaluate an arithmetic expression using stack and show how the expression 3∗(5−3)3*(5-3) will be evaluate.

Answer: Use two stacks: a value stack and an operator stack. Scan the infix expression left to right. Push operands on the value stack; push ( on the operator stack; when ) is read, pop operators and apply them to the top two values until ( is reached; at the end apply all remaining operators. In postfix form the same expression is 3 5 3 - *, evaluated with one stack: push 3, 5, 3; on - pop 3 and 5, push 5-3=2; on * pop 2 and 3, push 3*2=6. Trace of 3∗(5−3)3*(5-3):

Token Value stack Operator stack Action
3 3 empty push operand
* 3 * push operator
( 3 * ( push
5 3, 5 * ( push operand
- 3, 5 * ( - push operator
3 3, 5, 3 * ( - push operand
) 3, 2 * pop -: 5-3=2
end 6 empty pop *: 3*2=6

Converting and evaluating expressions. An infix expression places the operator between its operands and needs parentheses and precedence rules to remove ambiguity. A postfix expression places the operator after its operands and is unambiguous without parentheses because the order of operators is exactly the order of evaluation. A prefix expression places the operator before its operands, also called polish notation. To convert infix to postfix, scan the expression from left to right, output operands immediately, push opening parentheses and operators onto a stack, pop operators of higher or equal precedence to the output before pushing a new operator, and on a closing parenthesis pop until the matching opening parenthesis. After the scan, pop all remaining operators. For the given expression with nested parentheses and an exponent, the trace shows the stack growing and shrinking at each step and the output accumulating operands and operators in postfix order. To evaluate a postfix expression, scan left to right, push operands onto a stack, and when an operator appears pop the top two operands, apply the operator and push the result. Evaluating three times the quantity five minus three therefore pushes three, five and three, subtracts to two, multiplies by three and yields six. Parentheses are needed only in infix because the position of an operator alone does not determine which operands it joins; in postfix the position fixes the grouping completely. A good answer gives the algorithm, traces the stack and output at each significant step, states the final expression and evaluates a sample expression with the stack contents shown.

Result: The expression evaluates to 6. Equivalent postfix is 3 5 3 - *; each operator is applied when enough operands are available, so evaluation is O(n).

3∗(5−3)3*(5-3)
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

  • Two-stack method: value stack for operands, operator stack for operators and parentheses
  • On ')' apply stacked operators until '('; at end apply all remaining operators
  • Trace: 3, , (, 5, -, 3, ) gives 5-3=2 then 32=6
  • Postfix form 3 5 3 - * uses one stack; final value = 6
Q4b7MUnit 2 — Dequeue and Priority Queue
Core Concept

A double ended Queue (deque) is a linear list in which additions may be made at either end. Obtain a data representation mapping a deque into one dimensional array. Write C function to add and delete elements from either end of deque.

Answer: A deque is mapped onto a one-dimensional array of size N using two indices, front and rear. To avoid shifting, treat the array as circular: after index N-1 comes 0. Initially front = rear = -1 (empty). Insertion at front decrements front modulo N; insertion at rear increments rear modulo N; deletion reverses these moves. Full when (rear+1) % $N ==$ front, empty when front -1.

#include <stdio.h>
#define N 10
int dq[N], front = -1, rear = -1;
int isfull(void) { return (rear+1)%N == front; }
void addFront(int x) {
    if (isfull()) return;
    if (front == -1) front = rear = 0;
    else front = (front-1+N) % N;
    dq[front] = x;
}
void addRear(int x) {
    if (isfull()) return;
    if (front == -1) front = rear = 0;
    else rear = (rear+1) % N;
    dq[rear] = x;
}
int deleteFront(void) {
    if (front == -1) return -1;
    int x = dq[front];
    if (front == rear) front = rear = -1;
    else front = (front+1) % N;
    return x;
}
int deleteRear(void) {
    if (front == -1) return -1;
    int x = dq[rear];
    if (front == rear) front = rear = -1;
    else rear = (rear-1+N) % N;
    return x;
}

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: All four operations run in O(1) using circular indexing; the circular mapping reuses slots freed by deletions and avoids the false-full condition of a linear array deque.

N==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

  • Map deque to a circular 1-D array with front and rear indices
  • Empty: front = rear = -1; full: (rear+1) mod N == front
  • addFront decrements front mod N; addRear increments rear mod N
  • deleteFront increments front; deleteRear decrements rear; all O(1)
Q5a7MUnit 3 — Selection
Predicted

Write a C program for sorting 100 integer numbers using selection sort procedure. Discuss the worst-case time complexity of the algorithms.

Answer: Selection sort repeatedly finds the minimum element in the unsorted suffix and swaps it into position i.

#include <stdio.h>
#define N 100
int main(void) {
    int a[N], i, j, min, t;
    for (i = 0; i &lt; N; i++) scanf("%d", &a[i]);
    for (i = 0; i &lt; N-1; i++) {
        min = i;
        for (j = i+1; j &lt; N; j++)
            if (a[j] &lt; a[min]) min = j;
        if (min != i) { t = a[i]; a[i] = a[min]; a[min] = t; }
    }
    for (i = 0; i &lt; N; i++) printf("%d ", a[i]);
    return 0;
}

Worst-case complexity: the inner loop always scans all remaining elements, so comparisons = (n−1)+(n−2)+...+1=n(n−1)/2=Θ(n2)(n-1)+(n-2)+...+1 = n(n-1)/2 = \Theta(n^2), for every input (best, average and worst). Swaps are at most n-1, so the cost is comparison-dominated. Space is O(1); the sort is not stable.

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: 100 integers are sorted by n-1 passes of minimum selection; worst-case time Θ(n^2) (about 4950 comparisons for n=100), auxiliary space O(1).

(n−1)+(n−2)+...+1=n(n−1)/2=Θ(n2)(n-1)+(n-2)+...+1 = n(n-1)/2 = \Theta(n^2)
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

  • Selection sort: find minimum in suffix [i..n-1] and swap with position i
  • Program reads and sorts 100 integers with nested loops
  • Comparisons = n(n-1)/2 in all cases, so worst-case time Θ(n^2)
  • Space O(1), not stable; about 4950 comparisons for n=100
Q5b7MUnit 3 — Binary Search
Core Concept

Write a program in C language to implement binary search algorithm. Also discuss the average behavior of the algorithm.

Answer: Binary search requires a sorted array. Compare the key with the middle element; if equal, stop; if smaller, search the left half; if larger, search the right half.

#include <stdio.h>
int binary(int a[], int n, int key) {
    int lo = 0, hi = n-1, mid;
    while (lo &lt;= hi) {
        mid = lo + (hi-lo)/2;
        if (a[mid] == key) return mid;
        if (a[mid] > key) hi = mid-1; else lo = mid+1;
    }
    return -1;
}
int main(void) {
    int a[6] = {2,5,8,12,16,23}, n = 6, key = 12;
    printf("%d
", binary(a, n, key));
    return 0;
}

Trace for key 12: lo=0,hi=5,mid=2 -> a[2]=8 < 12, so lo=3; mid=4 -> a[4]=16 > 12, so hi=3; mid=3 -> a[3]=12 found, returns index 3. Average behavior: Each iteration halves the search range, so after k steps at most n/2kn/2^k items remain; k = O(log n). Average and worst case Θ(log n) comparisons, best case Θ(1) when the middle element matches. Space O(1) iterative, O(log n) recursive. It far outperforms linear search Θ(n) on sorted data.

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: The C function returns the index of key or -1; average time Θ(log n).

n/2kn/2^k
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

  • Binary search needs a sorted array; compare with middle and discard half
  • C function uses lo/hi bounds and returns index or -1
  • Trace key 12 in 2,5,8,12,16,23 finds index 3 after 3 probes
  • Average and worst time Θ(log n), best Θ(1), space O(1) iterative
Q6a7MUnit 4 — Basic terminology used with Tree
Core Concept

If EE and II denotes the external and internal path length of a binary tree having nn internal nodes then show that E=I+2nE=I+2n.

Answer: In an extended binary tree every internal node has exactly two children; external nodes are the leaves (shown as squares). Internal path length II = sum of depths of all internal nodes; external path length EE = sum of depths of all external nodes. Claim: E=I+2nE = I + 2n, where n is the number of internal nodes. Proof by induction on n:

  • Base n=0: the tree is one external node at depth 0, so I=0, E=0, and E = I+2n holds.
  • Inductive step: assume the result for a tree with k internal nodes. Take a tree T with n internal nodes. Pick an internal node v whose children are both external nodes (a deepest internal node). Replace v by an external leaf, giving T' with n-1 internal nodes.
  • Removing the two children of v reduces E by 2(d+1)2(d+1) where d is the depth of v (two external nodes at depth d+1), and adding the new external node increases E by d. Net change: E(T)=E(T′)+d+2E(T) = E(T') + d + 2.
  • The internal path length changes only by losing v: I(T)=I(T′)+dI(T) = I(T') + d.
  • By induction E(T′)=I(T′)+2(n−1)E(T') = I(T') + 2(n-1), hence E(T)=I(T′)+2n−2+d+2=I(T)+2nE(T) = I(T') + 2n - 2 + d + 2 = I(T) + 2n. Check: a single internal node with two external leaves: I=0, E=1+1=2, and I+2n=0+2=2.

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: For every extended binary tree with n internal nodes, E=I+2nE = I + 2n.

E=I+2nE = I + 2n 2(d+1)2(d+1) E(T)=E(T′)+d+2E(T) = E(T') + d + 2
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.
E = I + 2n: every internal node adds two external links when extended

Key Points

  • I = sum of depths of internal nodes; E = sum of depths of external (leaf) nodes
  • Proof by induction: remove a deepest internal node with two external children
  • E(T) = E(T') + d + 2 and I(T) = I(T') + d
  • Therefore E = I + 2n; check single root: I=0, E=2, n=1
Q6b7MUnit 4 — Huffman coding using Binary Tree
Core Concept

Suppose character a, b, c, d,e,f has probabilities 0.07, 0.09, 0.12, 0.22, 0.23, 0.27 respectively. Find an optional Huffman code and draw the Huffman tree. What is the average code length?

Answer: Huffman coding repeatedly merges the two lowest-probability nodes; the parent gets their sum, and edges are labelled 0 (left) and 1 (right). Merge sequence:

  1. a(0.07) + b(0.09) = 0.16
  2. c(0.12) + ab(0.16) = 0.28
  3. d(0.22) + e(0.23) = 0.45
  4. f(0.27) + cab(0.28) = 0.55
  5. de(0.45) + fcab(0.55) = 1.00 (root) Huffman tree:
                    1.00
                  0/   \1
               0.45      0.55
              0/  \1   0/    \1
             d    e   f     0.28
                         0/    \1
                        c      0.16
                             0/   \1
                             a     b

Codes (root-to-leaf edge labels): d=00, e=01, f=10, c=110, a=1110, b=1111. Average code length: 0.22(2)+0.23(2)+0.27(2)+0.12(3)+0.07(4)+0.09(4)=0.44+0.46+0.54+0.36+0.28+0.36=0.22(2)+0.23(2)+0.27(2)+0.12(3)+0.07(4)+0.09(4) = 0.44+0.46+0.54+0.36+0.28+0.36 = 2.44 bits/symbol.

Building optimal prefix codes. Huffman coding constructs a prefix code for a set of symbols with known probabilities so that no code word is the prefix of another and the average code length is minimal. The algorithm repeatedly combines the two symbols or subtrees with the smallest probabilities into a new node whose probability is their sum, assigning zero to one branch and one to the other, until only one root remains. Tracing from the root to each leaf gives that symbol's code word. For probabilities of seven, nine, twelve, twenty two, twenty three and twenty seven percent, the first combination is seven plus nine equals sixteen, then twelve plus sixteen equals twenty eight, then twenty two plus twenty three equals forty five, then twenty eight plus twenty seven equals fifty five, and finally forty five plus fifty five gives one hundred. Reading the branches gives code words of increasing length for more frequent symbols, with the most probable symbols receiving the shortest codes. The average code length is the sum of each probability times its code length, which is close to the entropy of the source and is strictly less than what a fixed length code would require for six symbols. A binary tree is essential to the algorithm because the path from root to leaf naturally produces a prefix free binary code and the combining step is exactly the creation of an internal node with two children. A good answer lists each combining step with the resulting probabilities, draws the final tree, gives one possible set of codes, notes that codes may differ by swapping zero and one branches, and computes the average length. Mentioning that the result is optimal among prefix codes and that ties can be broken arbitrarily shows understanding of the algorithm's correctness.

Result: The optimal prefix-free codes are d=00, e=01, f=10, c=110, a=1110, b=1111, with average length 2.44 bits per symbol; higher-probability symbols get shorter codes.

0.22(2)+0.23(2)+0.27(2)+0.12(3)+0.07(4)+0.09(4)=0.44+0.46+0.54+0.36+0.28+0.36=0.22(2)+0.23(2)+0.27(2)+0.12(3)+0.07(4)+0.09(4) = 0.44+0.46+0.54+0.36+0.28+0.36 =
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.
100 4555 2817 e 0.27f 0.23d 0.22 combine lowest probabilities first; frequent symbols get shorter codes

Key Points

  • Merge order: ab=0.16, cab=0.28, de=0.45, fcab=0.55, root=1.00
  • Codes: d=00, e=01, f=10, c=110, a=1110, b=1111
  • Average length = 0.222+0.232+0.272+0.123+0.074+0.094 = 2.44
  • Leaf paths make the code prefix-free and higher probabilities get shorter codes
Q7a7MUnit 5 — Minimum Cost Spanning Trees: Prims and Kruskal algorithm
Survival ModePredictedRepeated

Find the minimum spanning tree using Prim’s algorithm for the graph shown below: -

Answer: A minimum spanning tree connects all vertices with n-1 edges and minimum total weight. Prim's algorithm grows one tree from an arbitrary start vertex. Algorithm:

  1. Start with any vertex s in the tree set T; keep an array low[v] = cheapest edge weight from T to v (infinity if none), and parent[v].
  2. Repeat n-1 times: choose the vertex u not in T with minimum low[u]; add edge (parent[u], u) to the MST and put u in T.
  3. For each neighbour v of u not in T, if weight(u,v) &lt; low[v], set low[v] = weight(u,v) and parent[v] = u. Time O(n2)O(n^{2}) with an array, O((V+E) log⁡\log V) with a priority queue. Illustration (graph with edges AB=2, AC=3, BC=1, BD=4, CD=5, CE=7, DE=6) start at A. | Step | T | Cheapest crossing edge | Add | | --- | --- | --- | --- | | 1 | A | AB=2 | AB | | 2 | A,B | BC=1 | BC | | 3 | A,B,C | BD=4 | BD | | 4 | A,B,C,D | DE=6 | DE | MST edges: AB(2), BC(1), BD(4), DE(6); total cost = 13, with 5 vertices and 4 edges and no cycle.

Spanning trees and shortest paths. A spanning tree connects all vertices of a connected graph with exactly n minus one edges and no cycles. A minimum spanning tree is the spanning tree with the smallest total edge weight. Prim's algorithm starts from one vertex and repeatedly adds the cheapest edge that connects a vertex in the growing tree to a vertex outside it. Kruskal's algorithm sorts all edges by weight and adds each edge if it does not form a cycle, using a disjoint set structure to test connectivity. Both produce a minimum spanning tree, Prim being better for dense graphs and Kruskal for sparse graphs. Shortest path problems differ: Dijkstra's algorithm finds the shortest path from one source to all other vertices in a graph with nonnegative weights by repeatedly selecting the unvisited vertex with the smallest tentative distance and relaxing its outgoing edges. Floyd Warshall finds shortest paths between every pair of vertices by dynamic programming, considering each vertex as a possible intermediate point and updating the distance matrix. The transitive closure of a graph records which vertices are reachable from which others and can be computed by the same Warshall iteration using boolean values. A good answer distinguishes minimum spanning tree from shortest path, gives the steps of each algorithm, applies Prim or Dijkstra to the given graph with a table of selected edges or tentative distances, states complexities and explains what the matrix update means. Mentioning that Dijkstra fails with negative edges while Bellman Ford handles them is a useful boundary condition, and noting that a minimum spanning tree minimises total weight while a shortest path minimises one route shows the essential conceptual difference.

Result: Prim's algorithm always takes the cheapest edge leaving the current tree; the resulting MST has n-1 edges and minimum total weight (13 in the illustration).

O(n2)O(n^{2}) log⁡\log
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.
Prim's minimum spanning tree ABCD start at A, add cheapest crossing edge each time; green edges are in the MST

Key Points

  • MST connects all n vertices with n-1 edges and minimum total weight
  • Prim: start anywhere, repeatedly add cheapest edge from built tree to an outside vertex
  • Maintain low[v] and parent[v]; update when a cheaper crossing edge is found
  • Complexity O(n^2) array or O((V+E) log V) heap; illustration MST cost 13
Q7b7MUnit 5 — Data Structure for Graph Representations: Adjacency Matrices
Predicted

Write a program in C language to compute the indegree and outdegree of every vertex of a directed graph when the graph is represented by an adjacency matrix.

Answer: For a directed graph stored as adjacency matrix A, A[i][j] = 1 means an arc from i to j. The outdegree of i is the number of 1s in row i; the indegree of j is the number of 1s in column j.

#include <stdio.h>
#define N 10
int main(void) {
    int A[N][N], n, i, j, indeg[N] = {0}, outdeg[N] = {0};
    scanf("%d", &n);
    for (i = 0; i &lt; n; i++)
        for (j = 0; j &lt; n; j++) scanf("%d", &A[i][j]);
    for (i = 0; i &lt; n; i++)
        for (j = 0; j &lt; n; j++)
            if (A[i][j]) { outdeg[i]++; indeg[j]++; }
    for (i = 0; i &lt; n; i++)
        printf("vertex %d: indeg=%d outdeg=%d
", i, indeg[i], outdeg[i]);
    return 0;
}

Example: edges 0->1, 0->2, 1->2, 2->0 give matrix rows 0: 0 1 1, 1: 0 0 1, 2: 1 0 0. Then vertex 0 has indeg 1 outdeg 2, vertex 1 has indeg 1 outdeg 1, vertex 2 has indeg 2 outdeg 1; total indegree = total outdegree = 3 = number of arcs.

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: Scanning each row accumulates outdegrees, scanning each column accumulates indegrees; time Θ(n²), space O(n)O(n) for the degree arrays.

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.
Adjacency matrix for indegree and outdegree row ioutdegree = row sum column sum gives indegree

Key Points

  • Adjacency matrix A[i][j]=1 means arc i to j
  • Outdegree of i = count of 1s in row i; indegree of j = count of 1s in column j
  • C program scans rows and columns into outdeg[] and indeg[] arrays
  • Time Θ(n²); sum of indegrees equals sum of outdegrees equals number of arcs