What is data structure? Give the classification of data structure in brief.
A data structure is a way of organising, storing and accessing data efficiently, such as arrays, stacks, queues, linked lists, trees and graphs. It is classified as linear when elements form a sequence, as in arrays and lists, or nonlinear when elements form a hierarchy or network, as in trees and graphs.
Key Points
Organises and stores data
Linear structures are sequential
Nonlinear include trees and graphs
Q1b2MUnit 1 — Single and Multidimensional Arrays
Core Concept
What is the difference between array implementation and linked list implementation?
An array stores elements in contiguous memory, giving constant time random access but costly insertion and deletion because elements shift. A linked list stores nodes connected by pointers, giving constant time insertion at a known position but linear time search. Arrays use less overhead; lists grow dynamically.
Key Points
Array contiguous and indexable
List uses pointers
Different access and insertion costs
Q1c2MUnit 1 — Time and Space Complexity
Core Concept
What do you understand by polish notion?
Polish notation, also called prefix notation, places an operator before its operands, for example plus A B instead of A plus B. Because the operator comes first, the expression is unambiguous without parentheses, and it can be evaluated easily with a stack by scanning from right to left.
Key Points
Operator precedes operands
No parentheses needed
Example + A B
Q1d2MUnit 2 — Abstract Data Type
Core Concept
Write the difference between stack and queue in Data Structure.
A stack is last in first out: insertion and deletion happen at the same end called the top, and it is used for expression evaluation and function calls. A queue is first in first out: insertion at the rear and deletion at the front, and it is used for scheduling and buffering. Their insertion and deletion ends differ.
Key Points
Stack is LIFO at one end
Queue is FIFO at two ends
Different applications
Q1e2MUnit 4 — Complete Binary Tree
Core Concept
Explain the term Complete Binary Tree.
Answer:(a) Binary Search Tree (BST): A binary tree in which left-subtree keys are less than the node key and right-subtree keys are greater. Search/insert/delete cost O(h), where h is the height; O(log n) when balanced, O(n) when skewed. Inorder traversal yields keys in sorted order. Used for dictionaries, indexing and expression trees.
(b) Complete Binary Tree: A binary tree in which all levels except possibly the last are completely filled and the last level has nodes as far left as possible. For n nodes, height = floor(log2 n). It can be stored compactly in an array: parent of i is (i-1)/2, left child 2i+1, right child 2i+2. This is the shape used by binary heaps.
A level 0
/ \
B C level 1
/ \ /
D E F level 2 (filled left to right)
(c) Extended Binary Tree: A binary tree in which every internal node has exactly two children; empty child pointers are replaced by external (leaf) nodes, usually drawn as squares. If there are n internal nodes there are n+1 external nodes, and the path lengths satisfy E = I + 2n. Used to derive tree properties and external path length results.
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: BST orders keys for O(h) search; a complete tree maps perfectly to an array (heap storage); an extended tree fills every empty child with a leaf, giving n+1 external nodes.
O(h)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.
Complete tree: all levels full except last filled left to right; array indices 2i+1, 2i+2
Extended tree: every internal node has two children; n internal nodes give n+1 external leaves
Extended tree identity: E = I + 2n
Q1f2MUnit 2 — Iteration and Recursion- Principles of recursion
Core Concept
What do you mean by recursion? Discuss advantages and disadvantages of recursion.
Recursion is when a function calls itself on a smaller problem until a base case is reached. Its advantages are clean code for naturally recursive problems such as tree traversal and shorter implementations. Its disadvantages are function call overhead, greater stack memory use and the risk of infinite recursion or stack overflow if no base case is reached.
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:
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].
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.
For each neighbour v of u not in T, if weight(u,v) < low[v], set low[v] = weight(u,v) and parent[v] = u.
Time O(n2) with an array, O((V+E) 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)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.
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
What do you mean by complexity? Describe the asymptotic notation with a suitable diagram.
1. Meaning of complexity:
Complexity measures how the resource use of an algorithm grows as the input size n grows. Time complexity T(n) counts elementary operations (comparisons, assignments, arithmetic) as a function of n; space complexity 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)) iff there exist c>0 and n0>=0 such that 0<=f(n)<=cg(n) for every n>=n0. The function g is an eventual upper bound.
Omega:f(n)=Ω(g(n)) iff there exist c>0 and n0>=0 such that 0<=cg(n)<=f(n) for every n>=n0. The function g is an eventual lower bound.
Theta:f(n)=Θ(g(n)) iff there exist c1>0, c2>0 and n0>=0 such that 0<=c1g(n)<=f(n)<=c2g(n) for every n>=n0; that is, Θ(g)=O(g) intersect Ω(g), a tight bound.
Strict forms:f(n)=o(g(n)) when f(n)/g(n)−>0; f(n)=ω(g(n)) when f(n)/g(n)−>infinity.
3. Common growth-rate order (slowest to fastest):1<logn<n<nlogn<n2<n3<2n<n!.
Examples: array access 1; binary search logn; linear search n; merge sort nlogn; triple matrix loop n3; subset enumeration 2n; all permutations 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 n and the y-axis is operations / running time T(n). The curves lie close for small n but separate for large n, which is why constant factors are ignored. A Θ bound places f between two multiples of g beyond n0:
5. Application to the asked question:
For f(n)=3n+5 with g(n)=n: 3n+5<=8n for n>=2, so f=O(n); also 3n+5>=3n, so f=Ω(n); hence f=Θ(n). Binary search is Θ(logn), linear search Θ(n) and merge sort Θ(nlogn); the growth-rate order tells us which stays faster as n 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 n; O, Ω and Θ bound it above, below and tightly, and the diagram shows the standard growth-rate ladder.
T(n)S(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.
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
Q2b7MUnit 2 — Application of stack: Prefix and Postfix Expressions
Survival ModePredictedRepeated
Write an algorithm for converting infix expression into postfix expression. Trace your algorithm for infix expression A+(B∗C−(D/EF)∗G)∗H and give the resulting postfix expression.
1. Algorithm (stack-based infix to postfix):
Precedence: ^ = 3 (right-associative), * and / = 2, + and - = 1.
Add a sentinel ) to the expression and push ( on an empty stack.
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.
At the sentinel, pop all operators to output.
2. Trace of A+(B∗C−(D/EF)∗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)∗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 ')'
Write the algorithm of Insertion sort and sort the following list of numbers using insertion sort: 70, 17, 30, 80, 55, 1, 29, 67, 15.
Answer: Insertion sort grows a sorted prefix. For i = 1 to n-1, store key = A[i], shift every larger element of the sorted prefix one place right, then put key in the gap.
for i = 1 to n-1:
key = A[i]; j = i-1
while j >= 0 and A[j] > key:
A[j+1] = A[j]; j = j-1
A[j+1] = key
Passes on 70, 17, 30, 80, 55, 1, 29, 67, 15:
Pass i
key
List after insertion
1
17
17, 70, 30, 80, 55, 1, 29, 67, 15
2
30
17, 30, 70, 80, 55, 1, 29, 67, 15
3
80
17, 30, 70, 80, 55, 1, 29, 67, 15
4
55
17, 30, 55, 70, 80, 1, 29, 67, 15
5
1
1, 17, 30, 55, 70, 80, 29, 67, 15
6
29
1, 17, 29, 30, 55, 70, 80, 67, 15
7
67
1, 17, 29, 30, 55, 67, 70, 80, 15
8
15
1, 15, 17, 29, 30, 55, 67, 70, 80
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 nlogn 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 nlogn 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: Final sorted list is 1, 15, 17, 29, 30, 55, 67, 70, 80. Time O(n2) worst/average, O(n) best when already sorted; space O(1); stable and online.
nlognO(n)O(n2)
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: key = A[i]; shift larger elements right; insert key in the gap
Passes shown for all eight insertions of 70,17,30,80,55,1,29,67,15
Worst O(n^2), best O(n) on sorted input, O(1) extra space, stable
Q2d7MUnit 4 — Binary Search Tree
Survival ModePredictedRepeated
What do you mean by Binary Search Tree? Construct a Binary Search Tree by inserting the sequence 10, 12, 5, 4, 20, 8, 7, 15, 13.
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) 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.
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)
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
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)
Discuss doubly linked list. Write an algorithm to insert a node after a given node in a singly linked list.
1. Doubly linked list:
Each node has two links, prev and next, so it can be traversed in both directions:
NULL < - [A] < -> [B] < -> [C] -> NULL
head->prev = NULL and the last next = NULL; a tail pointer is often kept. Advantages over a singly linked list: forward and backward traversal, deletion given only the node pointer is O(1) (no need to find its predecessor), and easy implementation of deques. Disadvantages: one extra pointer per node and slightly more work to update links on insert/delete.
2. Insert after a given node in a singly linked list:
Let p be the node after which the new node must be inserted.
Algorithm insertAfter(p, value):
if p == NULL: stop (invalid position)
new = allocate node; new->data = value
new->next = p->next // link new node to the old successor
p->next = new // link p to the new node
return new
Order matters: if p->next is overwritten first, the rest of the list is lost. If the insertion is at the head, set new->next = head; head = new.
Example: list 10 -> 30, insert 20 after 10: new->next = 30, then 10->next = new, giving 10 -> 20 -> 30.
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: A doubly linked list carries prev and next links for two-way traversal; insertion after a known node in a singly list needs only two pointer assignments and runs in O(1).
For n≥1 elements the operation uses O(1) extra space.
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
Doubly linked node: data + prev + next; allows forward and backward traversal
Deletion at a known node is O(1); cost is one extra pointer per node
Insert after p: new->next = p->next, then p->next = new (order essential)
Example 10->30 becomes 10->20->30; O(1) once p is known
Q3b7MUnit 1 — Representation of Arrays: Row Major Order and Column Major Order
Core Concept
For a three‑dimensional array declared as A[1:10,−5:5,−10:5], (i) find the length of each dimension and the total number of elements, (ii) explain Row‑major order and Column‑major order with the formulae.
1. Length of each dimension:
For A[1:10,−5:5,−10:5] the length of a dimension is upper−lower+1:
Dimension 1: 10−1+1=10
Dimension 2: 5−(−5)+1=11
Dimension 3: 5−(−10)+1=16
Total elements =10×11×16=1760.
2. Row-major order (last subscript varies fastest):
With lower bounds L1=1,L2=−5,L3=−10 and lengths d1=10,d2=11,d3=16:
indexrow(i,j,k)=((i−L1)×d2+(j−L2))×d3+(k−L3)Address=Base+indexrow×size.
Example: A[2,0,−9]=((1)×11+5)×16+1=257 elements from the base.
3. Column-major order (first subscript varies fastest):indexcol(i,j,k)=(k−L3)×d1×d2+(j−L2)×d1+(i−L1)Address=Base+indexcol×size.
Example: A[2,0,−9]=1×10×11+5×10+1=161 elements from the base.
Bounds and layout of a three dimensional array. For an array declared with explicit lower and upper bounds, the length of each dimension is the upper bound minus the lower bound plus one. For dimensions one to ten, minus five to five and minus ten to five, the lengths are ten, eleven and sixteen, so the total number of elements is ten times eleven times sixteen, which is one thousand seven hundred and sixty. When an index is given, the offset from the lower bound is the index minus that lower bound. Row major order stores the last dimension as the fastest varying one, so the linear position of element i j k is the offset in the first dimension multiplied by the product of the other two lengths, plus the offset in the second dimension multiplied by the last length, plus the offset in the third dimension. Column major order would reverse this and make the first dimension vary fastest. Substituting the offsets gives the address by adding the product of the linear position and the element size to the base address. A good answer computes each dimension length explicitly, gives the total element count, writes the row major and column major position formulas with the correct products, substitutes the actual indices including the negative lower bounds and states the address with units. Showing the offset values before the formula avoids sign errors, which are the most common mistake in problems with negative bounds. Mentioning that the same formula generalises to any number of dimensions by taking products of the slower varying dimensions is a useful closing observation.
Result: Dimension lengths are 10, 11 and 16 (1760 elements); row-major and column-major differ only in which subscript is considered fastest-varying.
A[1:10,−5:5,−10:5]upper−lower+110−1+1=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.
Row-major index = ((i-L1)*d2 + (j-L2))*d3 + (k-L3): last index varies fastest
Column-major index = (k-L3)d1d2 + (j-L2)*d1 + (i-L1): first index varies fastest
Address = Base + index * element size
Q4a7MUnit 2 — Iteration and Recursion- Principles of recursion
Survival Mode
Write an algorithm for solving the Tower of Hanoi problem and explain its working with diagrams for 4 disks.
1. Problem & recursive algorithm:
Three pegs A (source), B (auxiliary), C (destination); n disks of increasing size on A. Rules: move one disk at a time, only the top disk, never place a larger disk on a smaller one.
Hanoi(n, source, aux, dest):
if n == 0: return
Hanoi(n-1, source, dest, aux) // move n-1 disks out of the way
print(move disk n: source -> dest)
Hanoi(n-1, aux, source, dest) // move them back on top
Recurrence M(n)=2M(n−1)+1, M(0)=0, so M(n)=2n−1; for 4 disks = 15 moves.
2. Diagrammatic states for 4 disks (disks 1=smallest ... 4=largest):
Start: A=[4,3,2,1] B=[] C=[]
After 6: A=[4] B=[] C=[3,2,1] (small tower moved to C)
After 7: A=[] B=[] C=[3,2,1] with disk4 on C? -> A=[] B=[] C=[4,3,2,1]
Final: A=[] B=[] C=[4,3,2,1]
A->B, 2. A->C, 3. B->C, 4. A->B, 5. C->A, 6. C->B, 7. A->B, 8. A->C, 9. B->C, 10. B->A, 11. C->A, 12. B->C, 13. A->B, 14. A->C, 15. B->C.
After move 7 the three smaller disks stand on B and disk 4 alone on C; moves 8-15 repeat the 3-disk process from B to C.
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 recursive decomposition moves 24−1=15 moves; the base case is n=0, and each call reduces n by one.
M(n)=2M(n−1)+1M(0)=0M(n)=2n−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
Algorithm: Hanoi(n-1,S,D,A); move disk n S->D; Hanoi(n-1,A,S,D)
Base case n=0; recurrence M(n)=2M(n-1)+1 = 2^n - 1
Four disks need 2^4-1 = 15 moves; list of moves A->B, A->C, B->C, ... ends at C
After move 7, disks 1-3 are on B and disk 4 on C, showing the recursive splitting
Q4b7MUnit 2 — Array and Linked Implementation of Stack in C
Core Concept
Write a C program to implement a stack using a singly linked list.
Answer: In a linked stack each node holds one value and a next pointer; top points at the newest node. Unlike an array stack there is no fixed capacity and no shifting.
#include <stdio.h>
#include <stdlib.h>
typedef struct node { int data; struct node *next; } Node;
Node *top = NULL;
void push(int x) {
Node *p = malloc(sizeof(Node));
if (!p) return;
p->data = x; p->next = top; top = p;
}
int pop(void) {
if (top == NULL) { puts("Underflow"); return -1; }
Node *p = top; int x = p->data; top = top->next; free(p); return x;
}
void display(void) {
for (Node *p=top; p; p=p->next) printf("%d ", p->data);
puts("");
}
int main(void) {
push(10); push(20); push(30); display();
printf("popped %d
", pop());
printf("popped %d
", pop()); display();
return 0;
}
Output:30 20 10, then popped 30, popped 20, then 10.
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: push inserts at the head in O(1) and pop removes the head in O(1); the linked list grows dynamically and needs no preallocated size.
For n≥1 elements the operation uses O(1) extra space.
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 node = data + next; top points to the most recent node
push: allocate node, set next=top, then top=new node (O(1))
pop: remove head, advance top, free node; underflow when top is NULL
Dynamic size, no shifting; example pushes 10,20,30 and pops 30,20
Q5a7MUnit 5 — Concept of Hashing & Collision resolution Techniques used in Hashing
Core Concept
What is hashing? Explain the division method to compute the hash function and the collision resolution strategies used in hashing.
Answer: Hashing maps a key directly to a table index with a hash function h(key), giving expected O(1) insertion and search. The table is called a hash table.
Division method:h(key)=keymodm, where m is the table size. It is simple and fast; m is usually chosen prime (or not close to a power of two) so that keys with common patterns spread evenly. Example: m=10, h(43)=3, h(165)=5, h(62)=2.
Collision resolution strategies:
Separate chaining (open hashing): every slot points to a linked list of all keys hashing there. 23 and 43 both map to 3, so bucket 3 holds 23 -> 43. Handles any load factor; needs pointer space.
Open addressing (closed hashing): all keys live in the table. On collision probe other slots:
linear probing: (h+i)modm (simple, but primary clustering);
double hashing: (h1+ih2)modm (best distribution).
Deletion in open addressing requires a DELETED marker so probe chains are not broken.
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: Hashing gives near-constant-time access; the division method uses h(key)=keymodm, and collisions are handled by chaining or by probing within the table (linear, quadratic, double).
h(key)h(key)=keymodm(h+i)modm
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
Hashing maps a key to a table index with h(key); expected O(1) search and insert
Division method: h(key) = key mod m, with prime m for even distribution
Collision strategies: separate chaining; open addressing (linear, quadratic, double hashing)
Open addressing needs a DELETED marker; chaining tolerates load factor above 1
Q5b7MUnit 5 — Heap Sort
Core Concept
Write an algorithm for Heap Sort and sort the sequence 18, 25, 45, 34, 36, 51, 43, 24 using it.
Answer: Heap sort builds a max-heap (array representation where parent i has children 2i+1 and 2i+2), then repeatedly swaps the root maximum with the last heap element, reduces the heap size and re-heapifies the root.
Algorithm:
BuildMaxHeap(A): for i = floor(n/2)-1 down to 0: siftDown(A, i, n)
for end = n-1 down to 1:
swap A[0] and A[end]
siftDown(A, 0, end)
siftDown compares node i with its children and swaps with the larger child while that child is bigger than the node.
Trace of 18, 25, 45, 34, 36, 51, 43, 24:
After BuildMaxHeap: 51, 36, 45, 34, 25, 18, 43, 24 (root 51 is the maximum; heap property holds).
Successive extractions place 51, 45, 43, 36, 34, 25, 24, 18 at the end of the array.
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 heap every parent is at least as large as its children, so the largest element is at the root; in a 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 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 nlogn 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: Heap sort runs in Θ(n log n) for build plus extraction in every case and uses O(1) extra space; it is in-place but not stable. The given sequence sorts to 18, 24, 25, 34, 36, 43, 45, 51.
maxminnlogn
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
Heap sort: build max-heap, then swap root with last element and sift down
Array heap: parent i has children 2i+1 and 2i+2
BuildMaxHeap of the sequence gives 51,36,45,34,25,18,43,24
Extraction order 51,45,43,36,34,25,24,18; sorted 18,24,25,34,36,43,45,51
Time Θ(n log n) all cases, space O(1), not stable
Q6a7MUnit 4 — Complete Binary Tree
Core Concept
Write short notes on (a) Binary Search Trees, (b) Complete Binary Tree, (c) Extended Binary Tree.
Answer:(a) Binary Search Tree (BST): A binary tree in which left-subtree keys are less than the node key and right-subtree keys are greater. Search/insert/delete cost O(h), where h is the height; O(log n) when balanced, O(n) when skewed. Inorder traversal yields keys in sorted order. Used for dictionaries, indexing and expression trees.
(b) Complete Binary Tree: A binary tree in which all levels except possibly the last are completely filled and the last level has nodes as far left as possible. For n nodes, height = floor(log2 n). It can be stored compactly in an array: parent of i is (i-1)/2, left child 2i+1, right child 2i+2. This is the shape used by binary heaps.
A level 0
/ \
B C level 1
/ \ /
D E F level 2 (filled left to right)
(c) Extended Binary Tree: A binary tree in which every internal node has exactly two children; empty child pointers are replaced by external (leaf) nodes, usually drawn as squares. If there are n internal nodes there are n+1 external nodes, and the path lengths satisfy E = I + 2n. Used to derive tree properties and external path length results.
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: BST orders keys for O(h) search; a complete tree maps perfectly to an array (heap storage); an extended tree fills every empty child with a leaf, giving n+1 external nodes.
O(h)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.
Complete tree: all levels full except last filled left to right; array indices 2i+1, 2i+2
Extended tree: every internal node has two children; n internal nodes give n+1 external leaves
Extended tree identity: E = I + 2n
Q6b7MUnit 4 — Concept & Basic Operations for AVL Tree
Survival ModePredictedRepeated
Insert the sequence 71, 41, 91, 56, 60, 30, 40, 80, 50, 55 into an AVL tree starting with an empty tree.
Answer: An AVL tree keeps the balance factor 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)
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.
Use Prim’s Algorithm to compute the Minimum Spanning Tree for the given weighted graph.
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:
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].
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.
For each neighbour v of u not in T, if weight(u,v) < low[v], set low[v] = weight(u,v) and parent[v] = u.
Time O(n2) with an array, O((V+E) 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)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.
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
Q7b7MUnit 5 — Transitive Closure and Shortest Path algorithm: Warshal Algorithm and Dijikstra Algorithm
Core Concept
Write and explain the Floyd‑Warshall algorithm to find all‑pair shortest paths. Apply it to the given graph.
Answer: Floyd-Warshall finds the shortest path between every pair of vertices by allowing intermediate vertices one at a time.
Algorithm:
D[i][j] = weight(i,j) (infinity if no edge; 0 on diagonal)
for k = 0 to n-1:
for i = 0 to n-1:
for j = 0 to n-1:
D[i][j] = min(D[i][j], D[i][k] + D[k][j])
After iteration k, D[i][j] is the shortest path whose intermediate vertices come only from {0..k}. The recurrence tries routing i to j through k; if it is cheaper, update. Time Θ(n³), space Θ(n²). A negative cycle makes some diagonal entries negative.
Illustration(A→B=3,A→C=10,B→C=4,B→D=8,C→D=2). Initial matrix has direct weights and ∞ elsewhere; after considering B, A->C improves to 3+4=7; after considering C, A->D becomes 7+2=9 and B->D becomes 4+2=6.
Final all-pairs matrix:
A B C D
A 0 3 7 9
B ∞ 0 4 6
C ∞ ∞ 0 2
D ∞ ∞ ∞ 0
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: Floyd-Warshall computes all-pairs shortest distances in Θ(n³) time using the update D[i][j] = min(D[i][j], D[i][k]+D[k][j]); the illustrated graph yields the matrix above.
(A→B=3,A→C=10,B→C=4,B→D=8,C→D=2)∞3+4=7
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
Floyd-Warshall: D[i][j] = min(D[i][j], D[i][k] + D[k][j]) for every k
Triple loop over k, i, j; after k, only vertices 0..k are allowed as intermediates
Time Θ(n³), space Θ(n²); handles negative edges but not negative cycles
Example final matrix: A->C=7 via B, A->D=9, B->D=6 via C