DSA - Data Structure & Algorithms, Past Papers, UOS Main Campus

Data Structures and Algorithms Past Paper 2018 – M.Sc IT 3rd Term UOS (CMP-3112)

Term3rd
Year2018
Course codeCMP-3112
AnswersSolved ✓

University of Sargodha M.Sc. IT 3rd term Data Structure & Algorithms (CMP-3112) paper, 2018 exam (80 marks, 2:30 hours). The paper has been retyped without the handwritten number on the original, and solved answers are given below for all 16 short questions and all subjective questions: recursive maximum, infix to postfix, heap sort step by step, swapping nodes in a doubly linked list, BST traversals, Dijkstra’s algorithm and in/out-degree, Euler and Hamiltonian tours with an adjacency matrix.

Solved answers

Q1 – Short answers (16 × 2)

i. Data structure: A particular way of organising and storing data in memory so that it can be accessed and modified efficiently, e.g. arrays, linked lists, stacks, queues, trees and graphs.

ii. Abstract Data Type with example: A logical model of data and its operations without implementation details. Example: Queue ADT – data: an ordered collection; operations: enqueue, dequeue, front, isEmpty. It can be implemented with an array or a linked list.

iii. Asymptotic notations: Notations that describe how running time grows with input size n: Big-O (upper bound), Big-Ω (lower bound) and Big-Θ (tight bound).

iv. Insertion vs selection sort: Insertion sort inserts each element into the sorted part by shifting (stable, O(n) for sorted input); selection sort selects the minimum and swaps it (not stable, always O(n²) comparisons, only n − 1 swaps).

v. Best sort for an already sorted list: Insertion sort (or bubble sort with a swap flag) – each element is compared once with its neighbour and no shifts happen, so it takes O(n) time.

vi. Enqueue: The operation that inserts a new element at the rear of a queue (after checking that the queue is not full) and updates the rear pointer.

vii. Stack vs linked list: A stack is an ADT with LIFO access only at the top (push/pop). A linked list is a concrete structure of nodes linked by pointers that allows insertion and deletion at any position; a stack can be implemented using a linked list.

viii. Evaluate 4 5 + 7 2 − *: 4 + 5 = 9; 7 − 2 = 5; 9 × 5 = 45.

ix. Breadth first traversal: Start at a vertex, visit all its neighbours first, then their neighbours, level by level, using a queue and marking visited vertices.

x. Purpose of merge in merge sort: To combine two already sorted halves into one sorted list in linear time, by repeatedly taking the smaller front element.

xi. Four fundamental rules of recursion: (1) Base case – solvable without recursion; (2) Make progress – each call moves towards the base case; (3) Design rule – assume the recursive calls work; (4) Compound interest rule – never solve the same instance in separate recursive calls.

xii. Expression tree: A binary tree representing an expression: leaves are operands and internal nodes are operators. In-order, pre-order and post-order traversals give the infix, prefix and postfix forms.

xiii. Advantage of heap over stack: A heap gives the minimum (or maximum) element in O(1) and removes it in O(log n), so it supports priority-based access; a stack only gives the most recently inserted element.

xiv. Connected graph: An undirected graph in which there is a path between every pair of vertices.

xv. Leaf node: A node of a tree with no children (degree 0).

xvi. Hash table: An array-based structure that stores keys at positions computed by a hash function, giving O(1) average-time insert, search and delete.

Q2 – Recursive maximum and infix to postfix

(i)

All C++ code below was compiled with g++ and tested.

int maxElement(int a[], int n) {
    if (n == 1) return a[0];                 // base case: one element
    int m = maxElement(a, n - 1);            // max of first n-1 elements
    return (a[n - 1] > m) ? a[n - 1] : m;
}

(ii) (m + n) * (k + p) / (g / b) ^ (a ^ b / c), with ^ having the highest precedence (right-associative) and * and / left-associative:

SymbolStackPostfix output
( m + n )m n +
**m n +
( k + p )*m n + k p +
//m n + k p + *
( g / b )/m n + k p + * g b /
^/ ^m n + k p + * g b /
(/ ^ (m n + k p + * g b /
a/ ^ (… g b / a
^/ ^ ( ^… g b / a
b/ ^ ( ^… a b
// ^ ( /… a b ^
c/ ^ ( /… a b ^ c
)/ ^… a b ^ c /
endm n + k p + * g b / a b ^ c / ^ /

Postfix: m n + k p + * g b / a b ^ c / ^ / (checked with a Python stack program).

Q3 – Heap sort of 2, 6, 7, 5, 10, 9, 2, 4

All C++ code below was compiled with g++ and tested.

void maxHeapify(int a[], int n, int i) {
    int largest = i, l = 2 * i + 1, r = 2 * i + 2;
    if (l < n && a[l] > a[largest]) largest = l;
    if (r < n && a[r] > a[largest]) largest = r;
    if (largest != i) {
        int t = a[i]; a[i] = a[largest]; a[largest] = t;
        maxHeapify(a, n, largest);
    }
}
void heapSort(int a[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--) maxHeapify(a, n, i);   // build max-heap
    for (int end = n - 1; end > 0; end--) {
        int t = a[0]; a[0] = a[end]; a[end] = t;               // move max to the end
        maxHeapify(a, end, 0);                                   // restore heap
    }
}

Step 1 – build a max-heap (heapify from the last internal node down to the root): 2 6 7 5 10 9 2 4 → 10 6 9 5 2 7 2 4.

            10
          /    \
         6      9
        / \    / \
       5   2  7   2
      /
     4

Step 2 – repeatedly swap the root with the last element and heapify the rest:

StepHeap partSorted part
Remove 109 6 7 5 2 4 210
Remove 97 6 4 5 2 29 10
Remove 76 5 4 2 27 9 10
Remove 65 2 4 26 7 9 10
Remove 54 2 25 6 7 9 10
Remove 42 24 5 6 7 9 10
Remove 222 4 5 6 7 9 10

Sorted: 2, 2, 4, 5, 6, 7, 9, 10. Heap sort takes O(n log n) time and sorts in place. (Steps checked with a Python program.)

Q4 – Swap two adjacent nodes in a doubly linked list (links only)

To swap node p with the next node q (p → q), only the pointers of p, q and their outer neighbours change; the data stays in place.

All C++ code below was compiled with g++ and tested.

struct DNode { int data; DNode* prev; DNode* next; };

void swapWithNext(DNode*& head, DNode* p) {
    DNode* q = p->next;
    if (q == nullptr) return;              // p is the last node: nothing to swap
    DNode* before = p->prev;               // node before p (may be NULL)
    DNode* after  = q->next;               // node after q  (may be NULL)

    if (before != nullptr) before->next = q; else head = q;   // q becomes first
    if (after  != nullptr) after->prev  = p;

    q->prev = before;  q->next = p;
    p->prev = q;       p->next = after;
}
// list 1 <-> 2 <-> 3, swapWithNext(head, node1)  ->  2 <-> 1 <-> 3

Q5 – Strictly binary trees, priority queue and BST

(i) Strictly binary tree: a binary tree in which every non-leaf node has exactly two children (no node has only one child). With n leaves it has 2n − 1 nodes. Example:

        A
       / \
      B   C
         / \
        D   E      (A and C have two children; B, D, E are leaves)

(ii) Priority queue: a queue in which each element has a priority and the element with the highest priority is removed first (elements with equal priority follow FIFO). It is implemented efficiently with a binary heap (insert and delete in O(log n)). Uses: CPU scheduling, Dijkstra’s algorithm, Huffman coding, event simulation.

(iii) BST for 45, 36, 76, 23, 89, 115, 98, 39:

            45
          /    \
        36      76
       /  \       \
     23    39      89
                     \
                     115
                     /
                   98
TraversalOrder
Pre-order45, 36, 23, 39, 76, 89, 115, 98
In-order23, 36, 39, 45, 76, 89, 98, 115
Post-order23, 39, 36, 98, 115, 89, 76, 45
Level-order (BFS)45, 36, 76, 23, 39, 89, 115, 98

Q6 – Dijkstra’s algorithm and directed graph G

(i) The source vertex is not printed in the question; taking a as the source. Undirected edges: a–b 3, a–c 5, a–d 6, b–d 2, c–d 2, c–e 6, c–f 3, c–g 7, d–f 9, e–f 5, e–g 2, f–g 1.

Step (vertex fixed)abcdefg
Start0∞∞∞∞∞∞
a0356∞∞∞
b (3)355 (via b)∞∞∞
c (5)5511812
d (5)511812
f (8)1189
g (9)119
e (11)11
ToDistanceShortest path
b3a → b
c5a → c
d5a → b → d
f8a → c → f
g9a → c → f → g
e11a → c → e (a → c → f → g → e is also 11)

(Verified with a Python implementation of Dijkstra’s algorithm.)

(ii) Edges of G: a→a (loop), a→b, a→c, a→e, b→d, c→b, c→c (loop), d→c, d→e, e→a, e→d, e→e (loop); f is isolated. A loop adds 1 to both in-degree and out-degree.

Vertexabcdef
In-degree223230
Out-degree412230

Both totals are 12 = number of edges. Euler tour: a directed graph has an Euler circuit only if in-degree = out-degree for every vertex (and the edges are connected); here a has out 4 ≠ in 2, and even an Euler path would need exactly one vertex with out − in = 1, but a has out − in = 2. So G has no Euler circuit or Euler path. Hamiltonian: a Hamiltonian path or circuit must visit every vertex, but f has no edges at all, so G has no Hamiltonian path or circuit. (Without f, the path a → b → d → e is not Hamiltonian because c is missing; a → e → d → c → b is a Hamiltonian path of the other five vertices.)

Adjacency matrix (row = from, column = to):

abcdef
a111010
b000100
c011000
d001010
e100110
f000000
Save this paper for offline studyDownload the question paper, or save the paper together with all solved answers as a PDF.
↓ Download Paper (JPG)

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.